The answer depends on what you want to do with your XML. If you want to create Java objects, use JAXB, as Matt Ball suggested.
If you want to do some things (i.e. execute some code) depending on the names of XML elements (or content of their attributes, or whatever), then most likely you will end up with endless if-else
. Why? Because you are branching your code depending on what you have in the XML.
You can go around it by:
- putting each branch inside a class (or a method) and use class loader (or reflection) to construct an instance of it (or call this method);
- in case of having a finite set of elements you must respond to, having a
HashMap<String, Method>
and populating it before parsing, then simply invoking method the hash gives you; this implies the use of reflection.
Both solutions negatively affect the speed, but greatly (in my opinion) increase the readability, reusability and understanding of your code.
You might consider using DOM instead of SAX. Drawback: loads the whole XML to the memory; advantage: you can navigate through the tree of elements nicely and always have the context of any element.
As for writing XML: very simple XML documents you can just write, they do not differ from regular text files (open a stream, write to it, close it). However, it is usually better to operate on the DOM tree and then save it; there are many tutorials about it.
If your software is going to be used often, and you rely on the structure of your XML document a lot, and want to avoid nasty crashes caused by misplaced elements, be sure to have a Schema (XSD) or a DTD for it and validate each XML document you load against it. It helps a lot ;)