本文介绍了在SAX解析期间确定根元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用SAX来解析XML文件。假设我希望我的应用程序处理具有根元素 animalList 的XML文件 - 如果根节点是其他东西,则SAX解析器应该终止解析。

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.

使用DOM,你可以这样做:

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.");
...

但我无法确定如何使用SAX - 我无法弄清楚如何告诉SAX解析器确定根元素。但是,我知道如何在任何时候停止解析(在发布)。

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

示例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>

谢谢。

推荐答案

虽然我上次多次使用SAX并且不记得API,但我认为处理程序接收的第一个标记是根元素。所以,你应该创建一个布尔类成员来指示你是否已经检查了第一个元素:

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

这篇关于在SAX解析期间确定根元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 22:48