views:

123

answers:

5

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.

A: 

Check Castor XML Mapping

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

YoK
A: 

Have a look at Apache Commons Digester.

mwittrock
Is Digester still an active project? I don't see any updated on their site since January 2009.
Blaise Doughan
+2  A: 

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

djna
Thanks, I read your blog post. You must have a great IDE when you can just right click on an XML file and then generate the XSD. I doesn't find this option in Eclipse that I'm using. I have to read up about JAXB.
Jonas
Check out the JAXB support being added to the Eclipse Dali project: http://www.eclipse.org/webtools/releases/3.2.0/NewAndNoteworthy/jpa.php
Blaise Doughan
+1  A: 

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:

Blaise Doughan
A: 

I really like Simple for converting XML to Java.

Mark