Is there a declarative way to parse XML to Java objects?

家住魔仙堡 提交于 2019-12-10 13:59:15

问题


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 follow 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.


回答1:


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




回答2:


I really like Simple for converting XML to Java.




回答3:


Have a look at Apache Commons Digester.




回答4:


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



回答5:


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.




回答6:


Check Castor XML Mapping

Here is documentation for same : http://www.castor.org/xml-mapping.html




回答7:


I finally found XStream that was easy to use and parses the XML in a declarative way.



来源:https://stackoverflow.com/questions/3495336/is-there-a-declarative-way-to-parse-xml-to-java-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!