【问题标题】:How can I parse XML that confirms to the 1.1 spec using Java and Xerces?如何使用 Java 和 Xerces 解析符合 1.1 规范的 XML?
【发布时间】:2012-03-07 22:10:45
【问题描述】:

我正在尝试解析包含符合 XML 1.1 spec 的 XML 内容的字符串。 XML 包含在 XML 1.0 规范中不允许但在 XML 1.1 规范中允许的字符引用(字符引用转换为 U+0001–U+001F 范围内的 Unicode 字符)。

根据Xerces2 website,,Xerces2 解析器支持解析 XML 1.1 文档。但是,我不知道如何告诉它我们尝试解析的 XML 包含符合 1.1 的 XML。

我正在使用 DocumentBuilder 来解析 XML(类似这样):

public Element parseString(String xmlString) {
    try {
          DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
          DocumentBuilder documentBuilder = dbf.newDocumentBuilder();

          InputSource source = new InputSource(new StringReader(xmlString));

      // Throws org.xml.sax.SAXParseException becuase of the invalid character refs
          Document doc = documentBuilder.parse(source);

          return doc.getDocumentElement();

    } catch (ParserConfigurationException pce) {
          // Handle the error
    } catch (SAXException se) {
          // Handle the error
    } catch (IOException ioe) {
          // Handle the error
    }
}

我已尝试设置 XML 标头以指示 XML 符合 1.1 规范...

xmlString = "<?xml version=\"1.1\" encoding=\"UTF-8\" ?>" + xmlString;

...但仍被解析为 1.0 XML(仍会生成无效字符引用异常)。

如何配置 Xerces 解析器以将 XML 解析为 XML 1.1?是否有其他解析器可以为 XML 1.1 提供更好的支持?

【问题讨论】:

    标签: java xml xml-parsing xerces xml-1.1


    【解决方案1】:

    See here 获取 xerces 支持的所有功能的列表。可能低于 2 个功能是您必须打开的。

    http://xml.org/sax/features/unicode-normalization-checking

    True:执行 Unicode 规范化检查(如 XML 1.1 建议的第 2.13 节和附录 B 中所述)并报告规范化错误。

    False:不报告 Unicode 规范化错误。

    http://xml.org/sax/features/xml-1.1

    正确:解析器同时支持 XML 1.0 和 XML 1.1。
    False:解析器仅支持 XML 1.0。
    访问:只读 自:Xerces-J 2.7.0 注意:此功能的价值取决于 SAX 解析器拥有的解析器配置是否已知支持 XML 1.1。

    【讨论】:

      【解决方案2】:

      不确定如何使用 Xerces 执行此操作,但 Woodstox 支持开箱即用的 XML 1.1。虽然它主要是一个 Stax 解析器,但它也实现了 SAX API(从 3.2 版开始)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-04
        • 2013-07-22
        • 1970-01-01
        • 2011-05-31
        • 2014-01-16
        • 1970-01-01
        • 2019-09-24
        相关资源
        最近更新 更多