简体   繁体   English

在使用JAXB进行解组时,如何忽略(有效)XML结构的大部分内容?

[英]How to ignore (efficiently) most part of an XML structure when unmarshalling with JAXB?

When processing a web service response with a quite complex XML structure, I am only interested with a very small subset of information. 在处理具有相当复杂的XML结构的Web服务响应时,我只对一小部分信息感兴趣。 Lets consider the using JAXB has to be used in this context. 让我们考虑在这种情况下必须使用JAXB。

As an example, lets say I am only interested in retrieving d (which can be modeled as a single JAXB bean): 举个例子,假设我只对检索d(可以建模为单个JAXB bean)感兴趣:

a
  b1
    c1
    c2
  b2
    d

What is the fastest recommended way to ignore everything else but retrieve d? 除了检索d之外,忽略其他所有内容的最快建议方法是什么?

I think the fastest way would depend on exactly how the xml is formatted. 我认为最快的方法取决于xml的格式。 Eg you could create your own InputStream that wraps the real InputStream and just be on the lookout for "<d>" to trigger you to start passing data through to jaxb. 例如,您可以创建自己的InputStream来包装真正的InputStream并且只是在寻找"<d>"以触​​发您开始将数据传递到jaxb。

eg 例如

   InputStream is = // get real stream
   JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" );
   Unmarshaller u = jc.createUnmarshaller();
   Object o = u.unmarshal( new MySpecialStream(is) );

If you needed a more xml-like approach then you could create your own XMLStreamReader that only passed on certain calls if you were inside a d element. 如果你需要更像xml的方法,那么你可以创建自己的XMLStreamReader ,如果你在d元素中,它只传递某些调用。

eg 例如

   JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" );
   Unmarshaller u = jc.createUnmarshaller();
   XMLStreamReader xsr = XMLInputFactory.newInstance().createXMLStreamReader( ... );
   Object o = u.unmarshal( new MyXSRWrapper(xsr) );

Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 ( JSR-222 ) expert group. 注意:我是EclipseLink JAXB(MOXy)的负责人,也是JAXB 2( JSR-222 )专家组的成员。

There are a couple of different ways that you could handle this use case: 您可以通过几种不同的方式处理此用例:

Option #1 - StreamFilter Any JAXB Implementation 选项#1 - StreamFilter任何JAXB实现

You could use a StAX XMLStreamReader with a StreamFilter to filter out the portions of the XML document that you don't wish to map to: 您可以将StAX XMLStreamReaderStreamFilter一起使用,以过滤掉您不希望映射到的XML文档部分:

Option #2 - @XmlPath in MOXy JAXB 选项2 - @XmlPath在莫西JAXB

You could use the @XmlPath extension in MOXy: 您可以在@XmlPath中使用@XmlPath扩展:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class A {

    @XmlPath("b2/d/text()")
    private String d;

}

For More Information 欲获得更多信息

使用XPath选择所需的元素作为DOM节点,并使用该选定节点解组。

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

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