views:

107

answers:

3

I have written a XML parser with DocumentBuilderFactory for a complex XML file. Because there are many different node types that there are many boilerplate code. For every node type (NodeName) I have a loop over the children and a switch for the possible children elements.

Is it possible only to register the needed code for the different node types and then run the parsing?

+2  A: 

Several ways:

  • Refactor repeated code into reuseable methods.
  • Make use of XPath to select specific nodes directly.
  • Convert XML to fullworthy Javabean with a tool, e.g. XMLBeans.
BalusC
+1  A: 

The Java DOM parsing API is indeed a bit boilerplate. There are some other libraries:

Bozho
A: 

Writing a custom parser may not be the way to go. If you merely needs to map XML into Java objects, a preexisting library or tool is best. Let someone else worry about boilerplate.

I'm a big fan of Apache Digester, which takes a bunch of rules and buuilds the Java beans for you. For a little more of a learning curve but more flexibility and power you could use Apache XMLBeans.

Uri