Mapping XML to an object in Java

微笑、不失礼 提交于 2019-11-30 04:12:50
informatik01

Short answer: Yes, there is such a solution.

It is called "XML data binding", or alternatively "O/X Mapping" (Object/XML Mapping), or "OXM". Converting an XML document to an object is called unmarshalling.
Converting (serializing) an object to an XML document is called marshalling.

NOTE:
The terms marshalling and unmarshalling relate NOT ONLY to Object/XML and vice versa transformation. Read here: Marshalling (Computer Science).

Java's own solution is called Java Architecture for XML Binding (JAXB). It is a specification described by JSR 222. JDK includes a JAXB implementation, so you (usually) don't need to download standalone Reference Implementation (RI) from the JAXB Project home page.

NOTE:
You can check, which version of JAXB your JDK has by using xjc (binding compiler), bundled with JDK: xjc -version


Useful links

Just google "JAXB tutorial", there are tons of them.


Important note:

JAXB is a specification and there are different implementations of it (including Reference Implementation). But these traditional implementations cannot use XPath, which is sad, because for the heavily nested XML files using XPath can be much more effective.

EclipseLink MOXy provides a JAXB implementation with many extensions. One of them is XPath based mapping. I found it extremely useful, when doing one of my projects, where OXM was involved.

Here are some related links:

Use JAXB, it's a standard Java way how to XML bindings - that means converting objects to XML and back. You can just apply few annotations on your class and that's basically everything you need to do so you can avoid creation your own custom XML parser.

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