Tuesday, March 19, 2013

Easy xml

Without going into pros and cons of XML-based data formats, we have to say, that they are very commonly used. So common, that probably everyone faced with them.
To deal with XML data Android Developer portal recommends to use XmlPullParser, which is an efficient and maintainable way to parse XML on Android. It's classic Pull Parser with its advantages and disadvantages. Obvious disadvantage here - you don't have DOM model, and with big complex xml file you will doomed to tedious work with infinite nextgetName and getText. On the other hand, standard DOM parser in java (Document object as an interface which represents serialized xml) can't boast with convenient API too. Of course, Google can help to find a tons of 3d party solutions for xml parsing, but let's have lightweight and simple xml parser with pseudo DOM model and convenient api for xml nodes access.
Let's called our utility class XmlNode. As you might guess XmlNode represents node of xml tree. Each Node must contains it's name, value and list of attributes. List of child nodes must be present too. Reference to parent node may also be useful. For easy search of the child elements by name is't useful to have map of node-name/XmlNode pairs. Of course, this approach (get child node by name) won't work correctly if we will have a few child nodes with the same name on the same level. But in most cases we know xml tree structure and can avoid this problem by getting all child nodes of current node (in most cases these nodes represents items of some list).
Sometimes some xml node may be present on certain level of xml tree or not. I do not like to deal with null data, so I propose to always return empty (not initialized) child node when it's requested from parent node. For this purpose we also will add initialization marker (which will be set to true) when node will be created during xml file parse. In case if node is not present in tree but it's requested from code user always will be able to check was this node initialized or not.
I won't leave pieces of code here, whole class can be found in github.