【问题标题】:Determine root Element during SAX parsing在 SAX 解析期间确定根元素
【发布时间】:2011-05-14 23:38:31
【问题描述】:

我正在使用 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>

谢谢。

【问题讨论】:

    标签: java xml sax


    【解决方案1】:

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

    boolean rootIsChecked = false;
    

    然后写在你的处理程序中:

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

    【讨论】:

      猜你喜欢
      • 2011-09-09
      • 2020-06-07
      • 2010-12-29
      • 2011-03-25
      • 2015-08-16
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多