开发者

How to Know Schema Before Unmarshalling

Scenario:

I am trying to refactor a code, which asks user to choose an xml file, which suppose to adhere to any of the 2 given schemas. Right now, the code is trying to unmarshal it using Schema A Unmarshaller. If th开发者_Python百科at fails it is trying to unmarshal it using Schema B Unmarshaller. In case both fails it is rejecting the file by displaying a proper message to the user.

Problem:

Here the program flow depends on Exception thrown by unmarshal().

Question:

Is there any way to know by which unmarshaller we should attempt to parse the file, so we go for the correct unmarshaller right away? Further, this would also help us in rejecting all irrelevant XML files, which doesn't conform to either schemas.


There are a few different options:

Option #1 - Create the JAXBContext on Multiple Domain Models

If the models for the two schemas are compatible (are completely independent, or share types that are annotated the same way), then just create the JAXBContext on all of the domain objects instead of having one per schema.

  • http://bdoughan.blogspot.com/2010/08/using-xmlanyelement-to-build-generic.html

Option #2 - StAX Input

If having different XML schemas means having different root elements I would create a StAX XMLStreamReader look at the root element and then choose which marshaller to use. Then unmarshal that XMLStreamReader.

Option #3 - Validate the XML Document First

You could use the javax.xml.validation APIs to validate the document first and then based on the results choose the unmarshaller.


Perhaps you should look at using a SAX parser and process the two structures manually in one handler. Another possibility is to create a new schema that allows the two options.

If I had complete control of the schemas I would look at the second option. If the response schemas were simple and/or shared a similar structure I would look at using SAX.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜