简体   繁体   English

JAXB仅解组XML文件的深层子集

[英]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. 我的应用程序收到一个很长的XML文档,我想用它来填充Java对象。

However, while there are tons of deeply-nested elements in the XML, I am only interested in a handful of them. 但是,尽管XML中有许多深层嵌套的元素,但我只对其中的少数感兴趣。 I am also only interested in going from XML-to-Java. 我也只对从XML到Java感兴趣。 I do not need the capability of marshalling my Java object back into XML. 我不需要将Java对象编组回XML的功能。

I would like to use JAXB for this if possible, since my application's dependencies already include Eclipselink MOXy anyway. 如果可能的话,我想使用JAXB,因为我的应用程序的依赖项无论如何已经包含Eclipselink MOXy。 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注释,并考虑使用它来注释我的Java类字段,如下所示:

...
@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. 但是,我不知道该name属性是否有效。 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. 无论如何,我都没有得到……编译器告诉我,@ @XmlElementWrapper仅在成员变量是Collection类型时才可以使用。 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: 我试着跳过@XmlElementWrapper批注,看看是否@XmlElement本身就能理解XPath值:

...
@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. 在运行时,Eclipselink只需在该字段中使用null实例化我的对象。

Is there something I am missing, or is what I'm trying to do even possible with JAXB at all? 是否有我缺少的东西,或者我正在尝试使用JAXB做什么?

This can be done with EclipseLink JAXB (MOXy) using the @XmlPath extension. 这可以通过使用@XmlPath扩展名的EclipseLink JAXB(MOXy)来@XmlPath

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

For More Information 欲获得更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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