开发者

Handling <property key='name' value='Foo' /> instead of <name>Foo</name> with JAXB

开发者 https://www.devze.com 2023-03-19 00:10 出处:网络
I have XML that looks like this: <thing> <property key=\'name\' value=\'Foo\' /> </thing>

I have XML that looks like this:

 <thing>
    <property key='name' value='Foo' />
 </thing>

I'd like to read that using JAXB.

I know that I can do

@XmlRootElement(name="thing")
public class Thing{

   @XmlElement(name="name")
   public String name;
开发者_C百科}

if the XML looked like

<thing>
   <name>Foo</name>
</thing>

, but what do I do for the XML layout above?


Note: I'm the EclipseLink JAXB (MOXy) lead, and a member of the JAXB 2.X (JSR-222) expert group.

You can use MOXy's @XmlPath extension for this use case:

@XmlRootElement(name="thing")
public class Thing{

   @XmlPath("property[@key='name']/@value")
   public String name;
}

For More Information:

  • http://bdoughan.blogspot.com/2011/03/map-to-element-based-on-attribute-value.html
  • http://bdoughan.blogspot.com/2011/05/specifying-eclipselink-moxy-as-your.html


if I am not wrong we need to create 2 classes one for thing and other for property as follows

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {"property"})
    @XmlRootElement(name = "thing")
    public class Thing {

        @XmlElement(required = true)
        protected Property property;

        public Property getProperty() {
            return property;
        }

        public void setProperty(Property value) {
            this.property = value;
        }

    }

and the other class will be

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "")
    @XmlRootElement(name = "property")
    public class Property {

        @XmlAttribute(required = true)
        protected String key;
        @XmlAttribute(required = true)
        protected String value;

        public String getKey() {
            return key;
        }

        public void setKey(String value) {
            this.key = value;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }

    }
0

精彩评论

暂无评论...
验证码 换一张
取 消