I have a web service which receives XML files and does unmarshalling to convert the XML file to an object. The problem is that my web service can receive different XML structures and has to do the correct unmarshalling.
So I receibe this kind of XML files:
<root>
<user>
<id>1234</id>
</user>
<XMLelements>
...
</XMLelements>
</root>
Notice that XMLelements is an example tag name, every XML file could have differents names.
So, I think, my web service workflow should be something like:
- It receives XML file.
- It checks user id.
- If user id == 1234
- UserA userA = unmarshalling(XMLFile)
- Else if user id == 5678
- UserB userB = unmarshalling(XMLFile)
- Else
- UserC userC = unmarshalling(XMLFile)
- If user id == 1234
So I receive different XML structures and for each one I have to do a different unmarshalling to get objects of different classes.
How can I perform this approach? I’m using Spring for marshalling (Metro).
Edit: This question didn’t receive any answer, maybe I’m not clear. I’ll try to explain it better:
I have a web service which is listening a url where receives XML files. Actually, in the same url path my web service receives two different XML schemas. How can I know how to do unmarshalling correctly? I mean, unmarshalling should return correct object when different XML schemas are passed.
There are a couple of different ways to support this use case.
OPTION #1 – DOM Approach
You could always use a DOM parser to convert the XML to a
Documentperform an XPath against it to get the value of theidelement and then unmarshal the document based on the resultOPTION #2 – SAX Approach
LookAheadUnmarshallerHandler
You could leverage a SAX parser and JAXB’s
UnmarshallerHandlermechanism and do the following:ContentHandlerthat queues up SAX events until the necessary information is discovered.JAXBContextbased on the value of theidelement.UnmarshallerHandlerfrom theJAXBContext.UnmarshallerHandler.UnmarshallerHandleron theXMLReaderas theContentHandler.UnmarshallerHandler.JAVA MODEL
The following object model is based on the classes you mention in your question.
UserA
UserB
UserC
INPUT (input.xml)
We will use the XML document from your question as the input for this example.
DEMO CODE
Output