November 14, 2009

Simple Java XML Parser

To continue my SN Project work I started to convert the simple object to data save format I had been using to save time during the semester into a xml based file system. This way when I update code it will not break saved game file due to class def not found exceptions. However I quickly ran into an issue that Java did not have a "simple" built in class to handle XML parsing and other free libraries where a little more complex then I was looking for, so although I usually try not to reinvent the wheel while programing, this time I wanted to try my hand at writing a simple Java XML parser.

What this basic XML parser does:  It looks for the starting tag < and then starts appending the tag characters to the node tag.  Then it hits > telling that the tag had ended and the data starts finally it looks for < for the next node.  There is also the case that another < is found in the data which indicates that a nested tag was found.  The older node is pushed on a stack and the parser moves up one child node and begins the tag and data read once more. This is repeated until no nodes are left on the stack indicating the root closing tag has been reached.

As a note:  I have removed most of the advanced checking and my custom xml build methods for security reasons, so you are on your own to add try/catch as needed.  Also, as I am not using any attributes in tags, so this parser does not read them.

Overall the code works well for the xml documents I am reading in, though for one class I may still look into a faster c based solution in the future, since I am working with a JNI library anyway.

You can check out the code HERE
As usual the code is free to use, but please give me some credit if it is used in a large project, or leave a comment about what it was used in.

No comments: