Using XPath Predicates for Mapping

This section demonstrates how the EclipseLink MOXy API uses XPath predicates to define an expression that specifiers the XML element's name. An XPath predicate is an expression that defines a specific object-to-XML mapping. As shown in previous examples, by default, JAXB will use the Java field name as the XML element name.

Understanding XPath Predicates

As described above, an XPath predicate is an expression that defines a specific object-to-XML mapping when standard annotations

re not sufficient. For example, the following snippet of XML shows a <data> element with two <node> sub-elements. If you wanted to create this mapping in a Java object, you would need to specify an XPath predicate for each <node> sub-element; for example, Node[2] in the following Java:

Mapping Based on Position

Mapping Based on an Attribute Value

Beginning with EclipseLink MOXy 2.3, you can also map to an XML element based on an Attribute value. In this exercise, you will annotate the JPA entity to render the XML document shown in Example 15-21. Note that all of the XML elements are named node but are differentiated by the value of their name attribute.

For each property, set the Xpath predicate by preceding the property declaration with the annotation @XmlPath(element-name[@attribute-name='value']); for example, for firstName, you would set the XPath predicate with this statement:

@XmlPath("node[@name='first-name']/text()")

Also local to the Customer class, declare the phoneNumber property as a List<PhoneNumber> type and assign it the value new ArrayList<PhoneNumber>().

"Self" Mappings

A "self" mapping occurs on one-to-one mappings when you set the target object's XPath to "." (dot) so the data from the target object appears inside the source object's XML element. This exercise uses the example in Mapping Based on an Attribute Value to map the Address information to appear directly under the customer element and not wrapped in its own element.

For the firstName and lastName properties, set the XmlPath annotation by preceding the property declaration with the annotation @XmlPath(element-name[@attribute-name='value']); for example, for firstName, you would set the XPath predicate with this statement:

@XmlPath("node[@name='first-name']/text()")

For the address property, set @XmlPath to "." (dot):

@XmlPath(".")
private Address address;

Also local to the Customer class, declare the phoneNumber property as a List<PhoneNumber> type and assign it the value new ArrayList<PhoneNumber>().

The rendered XML for the Customer entity would look like Example 15-25.