0

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.

PeakGen
  • 21,894
  • 86
  • 261
  • 463
  • You should at least know what data you are getting out of your XML. The XML is parsed before you can even get the element out of it. – nhahtdh Dec 02 '12 at 14:40
  • This is for a KPI. So, industry data – PeakGen Dec 02 '12 at 14:41
  • 1
    are you writing library for parsing of arbitrary XML? If not, you should know scheme of your XML documents and handle any unexpected elements as errors. – Victor Sorokin Dec 02 '12 at 14:44
  • Nothing will be provided. Only the XML. And, we are students anyway :)' – PeakGen Dec 02 '12 at 14:47
  • Is there a way to identify the main child element name (in this case, 'student') by overriding startElement() method of ContentHandler ? – PeakGen Dec 02 '12 at 14:48
  • OKOK. So you all say that we need to know the name of the main child element right? – PeakGen Dec 02 '12 at 14:55
  • 1
    @Sepala you should know scheme of XML doc, that is, what is root element, what it's children, what are their children and so on. Unless you writing your own implementation of SAX/DOM, which seems not to be the case. – Victor Sorokin Dec 02 '12 at 15:18
  • @VictorSorokin: My friend says we have to write a 'XSD or DTD' generator, then parse. Will it work? – PeakGen Dec 02 '12 at 15:34
  • @Sepala see http://docs.oracle.com/javaee/1.4/tutorial/doc/, chapter 5. – Victor Sorokin Dec 02 '12 at 15:51

1 Answers1

1

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.

facundofarias
  • 2,973
  • 28
  • 27
  • This is not a web solution anyway. This is a desktop app. I will look into the link :) – PeakGen Dec 02 '12 at 17:06
  • wow..This is very interesting. I don't know whether this will help me or not, but it is interesting!! +1 from me! – PeakGen Dec 02 '12 at 17:17