I'm fairly new to Java and am writing an app that needs an XML config file. The problem I have is that there doesn't seem to be any easy way to do this, which seems a bit strange. I've looked SAX and DOM and both seem quite complicated. Are there any other good API's out there? What's the best way to do this in Java? Thanks...
SAX and DOM are the "Standard" ways to approach parsing an XML file in Java.
There are alternatives to XML too.
Perhaps all you need is a properties file ?
Have you considered JSON?
Hi user303135,
I would recommend the Commons Configuration library: http://commons.apache.org/configuration/index.html Take a look at the HOWTOs to see how easy it is to get some information from an XML file.
All other libs I know involve either operating on the DOM directly or registering handlers for SAX parsing (which both involve a high overhead of code). JAXB is also an alternative but doesn't involve less overhead code than the former two.
Max
I've written a very simple API for precisely this reason. It uses the DOM parser underneath, but exposes a very simple and easy-to-use API that allows you to get to the XML data really easily. It's just a single Java file that you can use as a library in your code. Hope that helps.
A nice alternative to parsing the file yourself (especially for configuration purposes) is to use Apache Commons Digester.
You simply nominate what parts of the XML file will trigger which setters/methods you require, and Digester will do the rest. You can build arbitrarily complex configurations and the 'parsing' code remains trivial.
e.g.
digester.addObjectCreate( "addresses/address", Address.class );
digester.addBeanPropertySetter( "addresses/address/addressLine1", "addressLine1" );
creates an Address object and sets the first line of the address. See this tutorial for more info.
Alternatively XStream offers (possibly) the simplest XML-to-object conversion available in Java. To create an instance of a (say) Configuration
class from an input stream is a one-line operation.