1

我使用 JDOM2 从远程提要检索不受我控制的 XML。对于其中一个,我得到了这个错误:

名称 "" 对于 JDOM/XML 命名空间是不合法的:命名空间 URI 必须是非空且非空的字符串。

这是 XML 的示例:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Result xmlns="urn:XYZ" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" attributeA="1" attributeB="2" attributeC="3" xsi:schemaLocation="http://XYZ.com/ZYZ.xsd">
...
</Result>

如果我使用正则表达式删除 xsi:schemaLocation,该错误就会消失。

private String stripSchemaLocation(String xml) {
    return xml.replaceAll("xsi:schemaLocation=\"(.+?)\"", "");
}

这是我的 JDOM2 解析代码。它在 builder.build 上失败

// Schema location is causing problem with some xml.
xml = stripSchemaLocation(xml);

SAXBuilder builder = new SAXBuilder();

//@see http://xerces.apache.org/xerces-j/features.html
builder.setFeature("http://xml.org/sax/features/validation", false);
builder.setFeature("http://xml.org/sax/features/namespaces", false);
builder.setFeature("http://apache.org/xml/features/validation/schema", false);

//@see http://www.jdom.org/docs/faq.html#a0350
builder.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

org.jdom2.Document doc2 = builder.build(new InputSource(new StringReader(xml)));

// --Then doing XPath stuff with this XML--
4

1 回答 1

1

来自 JavaDoc:http://www.jdom.org/docs/apidocs/org/jdom2/input/SAXBuilder.html#setFeature(java.lang.String,%20boolean)

此外,在使用 JDOM 时绝不应该这样做:

builder.setFeature("http://xml.org/sax/features/namespaces", false);

请参阅包文档http://jdom.org/docs/apidocs/org/jdom2/input/sax/package-summary.html,其中指出:

Note that the existing JDOM implementations described above all set the generated XMLReaders to be namespace-aware and to supply namespace-prefixes. Custom implementations should also ensure that this is set unless you absolutely know what you are doing

您可能想要做的只是:

SAXBuilder builder = new SAXBuilder(XMLReaders.NONVALIDATING);

碰巧的是,它与以下内容相同:

SAXBuilder builder = new SAXBuilder();

因此您的代码将是:

SAXBuilder builder = new SAXBuilder();

//@see http://www.jdom.org/docs/faq.html#a0350
builder.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

org.jdom2.Document doc2 = builder.build(new InputSource(new StringReader(xml)));
于 2013-04-11T21:05:42.873 回答