简体   繁体   中英

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. Lets consider the using JAXB has to be used in this context.

As an example, lets say I am only interested in retrieving d (which can be modeled as a single JAXB bean):

a
  b1
    c1
    c2
  b2
    d

What is the fastest recommended way to ignore everything else but retrieve d?

I think the fastest way would depend on exactly how the xml is formatted. 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.

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.

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.

There are a couple of different ways that you could handle this use case:

Option #1 - StreamFilter Any JAXB Implementation

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:

Option #2 - @XmlPath in MOXy JAXB

You could use the @XmlPath extension in MOXy:

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

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

}

For More Information

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

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