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