Search code examples
javaxmliosaxsaxparser

Reading XML using Java - SAX Parser


Please have a look at the following link (The code here doesn't follow SAX)

http://viralpatel.net/blogs/parsing-reading-xml-file-in-java-xml-reading-java-tutorial/

Here, it seems like I must know the name of the main child elemenet (in this case, 'student' ), and parse it as a string to

NodeList studentList = docEle.getElementsByTagName("student");

So in here, it is like parsing XML with fixed element names. However, I have XML files, and I will never know names of the elements. Which means, in the first xml file, the tag name could be 'food', in the second xml file the tag name could be 'drinks' and so on. Which means, I will never know what elements will be there, and what are their names/tags.

How can I write new code/edit the given code, according to that? Please help.


Solution

  • See if XStream http://x-stream.github.io/ can solve this problem for you. It will de-serialize any valid xml. My other thought is switch to Groovy and use the XMLSlurper--a fabulous tool.