Woot4Moo
Woot4Moo

Reputation: 24336

JAXB retrieve individual elements from XML

I recently created a series of objects based on an XSD using the xjc tool. The issue I have is that I receive XML from a source that looks like so:

<foos>  
</foos>  
<foo>
</foo>
<foo_detail_1>  
</foo_detail_1>  
<foo_detail_2>  
</foo_detail_2>

Which is not ideal. My question is when I go to unmarshall the XML how can I create each individual object? That is like so:

Foo foo = (Foo)um.unmarshal("myXML.xml");  
Foo_Detail_1 fd = (Foo_Detail_1)um.unmarshal("myXML.xml");

Or is this more an exercise in utilizing XPath to populate these attributes and if so what is the correct way to approach this?

Upvotes: 2

Views: 115

Answers (1)

bdoughan
bdoughan

Reputation: 149047

OPTION #1 - Use JAXB with StAX

You can parse the XML with a StAX XMLStreamReader then advance to the foos element and unmarshal the instance of Foos. Then advance the XMLStreamReader to the foo element and unmarshal the instance of Foo, and so on.

For More Information

OPTION #2 - Create a Wrapper Object

You could create a wrapper object corresponding to the root element, then unmarshal an instance of that and get the individual objects from it.

Upvotes: 2

Related Questions