2

I'm using SAX Parser to convert XML into CSV format. Here, I need to fetch the root element of any given XML file. I know that I can do the task by using the following snippet.

if (!"book".equalsIgnoreCase(qName)) {
   .......
}

But I want to fetch the root element name from any given XML file automatically instead of explicitly defining it as "book". Because my intention is to generate CSV from any input XML file but with only using the SAX Parser. Can anyone help me with my problem? Thanks in advance!

Indi
  • 421
  • 9
  • 28

2 Answers2

3

There can only be a single root element in an XML document, and it will necessarily be the first element encountered, so simply save the element name (localName or QName – both are provided) the first time your startElement() callback is called.

kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • 2
    And note also that having saved it, you can abort further parsing by throwing a SAXException, which can save a lot of time if the file is large. – Michael Kay Oct 02 '19 at 16:41
1

Try this way,

public class DataHandler extends DefaultHandler {
   private String firstTag="";
   public void startElement(String uri, String name, String qName, Attributes atts) {
      i++;
      if(i==1) {
                firstTag=qName;
            } 
} // Saving 2nd line of tags (which is the root element) as firstTag

}


Then you can use firstTag accordingly where ever you use in the code.