名称“”对于JDOM / XML名称空间不合法

时间:2013-04-11 20:25:25

标签: java xml jdom jdom-2 xerces2-j

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

1 个答案:

答案 0 :(得分: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)));