Identify root element during SAX analysis

I use SAX to parse XML files. Suppose I want my application to only process XML files with the root element " animalList " - if the root of the node is something else, the SAX parser should stop parsing,

Using the 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 cannot figure out how to do this using SAX — I cannot figure out how to tell the SAX parser to determine the root element. However, I know how to stop parsing at any time (after seing Tom's decision ).

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>
    <devonRex>Tom</devonRex>
    <maineCoon>Keta</maineCoon>
  </cats>
</animalList>

Thank.

+3
source share
1

SAX API , , , , . , boolean class, , :

boolean rootIsChecked = false;

:

if (!rootIsChecked) {
    if (!"animalList".equals(elementName)) {
       throw new IllegalArgumentException("Wrong root element");
    }
    rootIsChecked = true;
}
// continue parsing...
+4

Source: https://habr.com/ru/post/1776649/


All Articles