1

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;
}

if the XML looked like

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

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

Thilo
  • 257,207
  • 101
  • 511
  • 656

2 Answers2

1

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:

bdoughan
  • 147,609
  • 23
  • 300
  • 400
  • Sweet. I'll give that a try. Is this on the roadmap for inclusion into the next version of JAXB? – Thilo Jul 07 '11 at 10:01
  • This works with MOXy 2.3. Maven gave me 2.2 at first, and 2.2 also has XmlPath, and it also binds stuff, but it seems to ignore the condition on the attribute. Thanks to Blaise's blog post where he announces this as a new feature in 2.3, I was able to figure that out. – Thilo Jul 07 '11 at 10:40
0

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;
        }

    }
ponds
  • 2,017
  • 4
  • 16
  • 11
  • If that is my only option with JAXB, I'll use XPath instead to manually write the unmarshaller code. – Thilo Jul 07 '11 at 08:53