Is there a declarative way to parse XML to Java objects?
I'm writing an import function of XML files to my Java application. I am using XOM to parse the XML files. The code for parsing the XML is not easy to understand, it is some hardcoded .getChild(3)
and so on. It is hard to fol开发者_运维技巧low the code compared to the declarative XML document.
Isn't there a more maintainable way to parse XML documents to Java objects? I would like to have it in a more declarative way, where I can specify what tags corresponds to what Java classes.
Have a look at JAX/B - fairly simple annotation-based approach. It's a standard Java API.
There are tools to generate Annotated Java classes from XSDs or sample XML files. I describe my use of it in my blog
I really like Simple for converting XML to Java.
Have a look at Apache Commons Digester.
Agreed JAXB (JSR-222) is the best solution. Note that JAXB is a spec meaning you have a choice of implementations:
- http://bdoughan.blogspot.com/2010/07/jaxb-xml-binding-standard.html
Standard JAXB allows you to specify the mappings by means of annotations, MOXy JAXB also allows you to specify your metadata via XML:
- http://wiki.eclipse.org/EclipseLink/Examples/MOXy/EclipseLink-OXM.XML
If you want a maintainable solution you need to break the one-to-one relationship between XML elements found in almost all XML binding solutions, and use XPath based mapping used in MOXy:
- http://bdoughan.blogspot.com/2010/07/xpath-based-mapping.html
- parse google geocode with xstream
The Simple XML framework uses annotations on field and method declarations as well as on class definitions to map XML to Java and back. Its many times more lightweight than JAXB (which pulls in tonnes of dependencies). In fact it has no external dependencies at all. And its faster too. I tried JAXB many times, but found the annotations and functionality awkward and cumbersome. Check out the Tutorial.
Check Castor XML Mapping
Here is documentation for same : http://www.castor.org/xml-mapping.html
I finally found XStream that was easy to use and parses the XML in a declarative way.
精彩评论