Jonas
Jonas

Reputation: 128777

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

Upvotes: 5

Views: 809

Answers (7)

ng.
ng.

Reputation: 7189

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.

Upvotes: 1

Jonas
Jonas

Reputation: 128777

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

Upvotes: 0

Mark
Mark

Reputation: 29119

I really like Simple for converting XML to Java.

Upvotes: 2

bdoughan
bdoughan

Reputation: 148977

Agreed JAXB (JSR-222) is the best solution. Note that JAXB is a spec meaning you have a choice of implementations:

Standard JAXB allows you to specify the mappings by means of annotations, MOXy JAXB also allows you to specify your metadata via 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:

Upvotes: 1

djna
djna

Reputation: 55887

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

Upvotes: 3

mwittrock
mwittrock

Reputation: 2931

Have a look at Apache Commons Digester.

Upvotes: 1

YoK
YoK

Reputation: 14505

Check Castor XML Mapping

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

Upvotes: 0

Related Questions