Determine root Element during SAX parsing
I am using SAX to parse XML files. Let's suppose that I want my application to only deal with XML files with root element "animalList" - if the root node is something else, the SAX parser should terminate parsing.
Using DOM, you would do it like this:
...
Element rootElement = xmldoc.getDocumentElement();
if ( ! rootElement.getNodeName().equalsIgnoreCase("animalList") )
throw new Exception("File is not an animalList file.");
...
but I can't ascertain how to do it using SAX - I can't figure out how to tell the SAX parser to determine the root element. However, I know how to stop parsing at any point (after seing Tom's solution).
Example XML file:
<?xml version="1.0" encoding="UTF-8"?>
<animalList version="1.0">
<owner>Old Joe</owner>
<dogs>
<germanShephered>Spike</germanShephered>
<australianTerrier>Scooby</australianTerrier>
<beagle>Ginger</beagle>
</dogs>
<cats>
<开发者_StackOverflow中文版devonRex>Tom</devonRex>
<maineCoon>Keta</maineCoon>
</cats>
</animalList>
Thanks.
Although I used SAX last time many years ago and do not remember the API by heart but I think that the first tag that your handler receives is the root element. So, you should just create a boolean class member that indicates whether you have already checked the first element:
boolean rootIsChecked = false;
Then write in your handler:
if (!rootIsChecked) {
if (!"animalList".equals(elementName)) {
throw new IllegalArgumentException("Wrong root element");
}
rootIsChecked = true;
}
// continue parsing...
精彩评论