我正在使用SAX来解析XML文件。假设我希望我的应用程序仅处理具有根元素“ animalList ”的XML文件 - 如果根节点是其他东西,则SAX解析器应该终止解析。
使用DOM,你会这样做:
...
Element rootElement = xmldoc.getDocumentElement();
if ( ! rootElement.getNodeName().equalsIgnoreCase("animalList") )
throw new Exception("File is not an animalList file.");
...
但我无法确定如何使用SAX来做 - 我无法弄清楚如何告诉SAX解析器确定根元素。但是,我知道如何在任何时候停止解析(在 Tom's solution之后)。
示例XML文件:
<?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>
感谢。
答案 0 :(得分:4)
尽管多年前我上次使用SAX并且不记得API,但我认为处理程序接收的第一个标记是根元素。因此,您应该创建一个布尔类成员,指示您是否已经检查了第一个元素:
boolean rootIsChecked = false;
然后写入你的处理程序:
if (!rootIsChecked) {
if (!"animalList".equals(elementName)) {
throw new IllegalArgumentException("Wrong root element");
}
rootIsChecked = true;
}
// continue parsing...