Reputation: 429
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!
Upvotes: 2
Views: 1107
Reputation:
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.
Upvotes: 1
Reputation: 111541
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.
Upvotes: 3