Reputation: 1926
Hi all i read some answers from other questions like that and didnt obtain a good answer...
So i would like to know some good api's to read and write xml strings. To read i'm thinking to use SAX i already started to write a xmlhandler with a state machine to process it but the handler starts to become big... on method
public void startElement(String uri, String name, String n, Attributes at)
i have a infinite else if tree, Is this normal and right ?
To write xml strings i have no idea yet...
thanks for your time
Upvotes: 0
Views: 392
Reputation: 7188
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:
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 ;)
Upvotes: 3