简体   繁体   中英

JAXB unmarshalling only a deeply-nested subset of an XML file

My application receives a very lengthy XML document, and I would like to use it to populate a Java object.

However, while there are tons of deeply-nested elements in the XML, I am only interested in a handful of them. I am also only interested in going from XML-to-Java. I do not need the capability of marshalling my Java object back into XML.

I would like to use JAXB for this if possible, since my application's dependencies already include Eclipselink MOXy anyway. However, I'm not sure how to grab only a handful of deeply nested element values. I looked at the @XmlElementWrapper annotation, and thought about using it to annotate my Java class fields like this:

...
@XmlElementWrapper(name="LEVEL_1/SUBLEVEL_1/YET_ANOTHER_SUBLEVEL")
@XmlElement(name="STATUS")
private String statusCode;
...

However, I don't know if that name attribute is valid. I don't get that far anyway... the compiler tells me that @XmlElementWrapper can only be used when the member variable is a Collection type. Most of the fields I'm trying to pull are single values.

I tried skipping the @XmlElementWrapper annotation, and seeing if @XmlElement alone would understand XPath values:

...
@XmlElement(name="LEVEL_1/SUBLEVEL_1/YET_ANOTHER_SUBLEVEL/STATUS")
private String statusCode;
...

While this doesn't cause a compile error, it doesn't work either. At runtime, Eclipselink simply instantiates my object with a null in this field.

Is there something I am missing, or is what I'm trying to do even possible with JAXB at all?

This can be done with EclipseLink JAXB (MOXy) using the @XmlPath extension.

@XmlPath("LEVEL_1/SUBLEVEL_1/YET_ANOTHER_SUBLEVEL/STATUS/text()")
private String statusCode;

For More Information

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM