How to map complex XML element to Java class property using JAXB

I need to map an XML fragment to a Java class using JAXB, but you have a difficult case. I have the following XML:

<person>
  <name part="first">Richard</name>
  <name part="last">Brooks</name>
</person>

and you need to map it to the next class

public class Person {

   private String firstName;
   private String lastName;
}

Could you help me figure out the JAXB annotations to make this possible?

+4
source share
2 answers

You can do this with MOXy , see @XmlPath .

@XmlPath("name[@part='first']/text()")
private String firstName;

@XmlPath("name[@part='last']/text()")
private String lastName;

Related questions:

+3
source

, , , Name:

@XmlRootElement
public class Person {
    @XmlElement(name="name")
    private List<Name> names;
    ...
}

public class Name {
   @XmlAttribute
   private String part; //would be set to "first" or "last"

   @XmlValue
   private String nameValue;
   ...
}
+1

All Articles