Fagoter
Fagoter

Reputation: 569

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

I need to map my XML snippet onto Java class using JAXB, but have a tricky case. I have the following XML:

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

and need to map it onto the following class

public class Person {

   private String firstName;
   private String lastName;
}

Could you please help me to figure out JAXB annotations to make it possible?

Upvotes: 4

Views: 1054

Answers (2)

lexicore
lexicore

Reputation: 43651

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:

Upvotes: 3

lewthor
lewthor

Reputation: 434

Here is one approach you could take, but would require you to create a separate class for 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;
   ...
}

Upvotes: 1

Related Questions