Access attribute of internal element in the most simple way

后端 未结 2 510
一整个雨季
一整个雨季 2020-12-20 06:12

Is there any way to do mapping with single java bean for such simple xml:


   some url
   

        
相关标签:
2条回答
  • 2020-12-20 06:28

    As I didn't want to create redundant classes in my package, the best solution I've found is:

    @XmlRootElement( name = "item" )
    public class Item {
    
        @XmlRootElement( name = "parent" )
        private static class ParentIdWrapper {
            @XmlAttribute( name = "id" )
            public String id;
        }
    
        @XmlElement( name = "item-url" )
        private String url;
    
        @XmlElement( name = "parent" )
        private ParentIdWrapper parentIdWrap;
    
        public String getParentId() {
            return this.parentIdWrap.id;
        }
    }
    
    0 讨论(0)
  • 2020-12-20 06:49

    You could use an XmlAdapter:

    ParentIdAdapter

    public class ParentIdAdapter extends XmlAdapter<ParentIdAdapter.AdaptedParentId, String> {
    
        public String unmarshal(AdaptedParentId value) {
            return value.id;
        }
    
        public AdaptedParentId marshal(String value) {
            AdaptedParentId adapted = new AdaptedParentId();
            adapted.id = value;
            return adapted;
        }
    
        public static class AdaptedParentId {
            @XmlAttribute
            public String id;
        }
    
    }
    

    Item

    @XmlRootElement( name = "item" )
    public class Item {
    
        @XmlElement( name = "item-url" )
        private String url;
    
        @XmlElement( name = "parent" )
        @XmlJavaTypeAdapter(ParentIdAdapter.class)
        private String parentId;
    }
    

    If you are using EclipseLink MOXy as your JAXB provider then you could leverage the @XmlPath extension to do the following:

    @XmlRootElement( name = "item" )
    public class Item {
    
        @XmlElement( name = "item-url" )
        private String url;
    
        @XmlPath("parent/@id")
        private String parentId;
    }
    
    0 讨论(0)
提交回复
热议问题