简体   繁体   中英

XML UnMarshalling based on child nodes

I recently got an old XML over HTTP API. It has few response types and all those responses have no namespace or type attributes. They all have the same root node and then different set of child nodes.

Is there a way in java to UnMarshall such XMLs ? It would be like using child nodes as discriminator fields. Two sample responses are given below.

<Response>
<A1/>
<A2/>
</Response>

<Response>
<B1/>
<B2/>
</Response>

The best approach really depends on what you want to do. If you just want to unmarshal the data you could define a model using JAXB, for instance, which includes all the potential child elements. Then when you unmarshalled an instance documents only the child elements actually present in the document would have values.

If you instead want to have separate models for the different response variations your best approach would be to use a BufferedInputStream and call mark() at the start, then read enough of the document with a pull parser such as XMLStreamReader to determine the actual response type. Then you can reset() the stream to the start of the document and start over using JAXB with the appropriate data model.

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