Determine root Element during SAX parsing

﹥>﹥吖頭↗ 提交于 2019-12-07 17:38:38

问题


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

Thanks.


回答1:


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...


来源:https://stackoverflow.com/questions/4265079/determine-root-element-during-sax-parsing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!