我用 Java 编写了一段代码,用于根据 xsd 架构验证 xml 文件。尽管在线 validator 返回肯定的结果,但 Java 中的 validator 不断失败。请在下面找到 xml/xsd 文件中的片段:
XML:
<?xml version = "1.0" encoding = "UTF-8"?>
<ns0:Root xmlns:ns0 = "URLA">
<ns0:DigitalAsset>
... XSD:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns="URLA"
targetNamespace="URLA"
elementFormDefault="qualified"
attributeFormDefault="unqualified">
<xs:import namespace="http://www.w3.org/XML/1998/namespace"/>
<xs:element name="Root">
错误:cvc-elt.1.a:找不到元素“ns0:Root”的声明
Java代码:
@Test
public void testXmlStructure(){
try {
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = parser.parse(new File("./resources/2449346_20151007_ProductTaxonomy.xml"));
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source schemaFile = new StreamSource(new File("./resources/Schema.xsd"));
Schema schema = factory.newSchema(schemaFile);
Validator validator = schema.newValidator();
validator.validate(new DOMSource(document));
} catch (IOException e){
Assert.fail(e.getMessage());
} catch(SAXException e1){
Assert.fail(e1.getMessage());
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
Assert.fail(e.getMessage());
}
}
不幸的是,数据很敏感。我将尝试用一些虚拟元素替换它并发布它。
非常感谢您的建议。
编辑:
你知道吗?我已将代码更改为以下内容并且有效:
@Test
public void testXmlStructure(){
try {
Source xmlFile = new StreamSource(new File("./resources/2449346_20151007_ProductTaxonomy.xml"));
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source schemaFile = new StreamSource(new File("./resources/Schema.xsd"));
Schema schema = factory.newSchema(schemaFile);
Validator validator = schema.newValidator();
validator.validate(xmlFile);
} catch (IOException e){
Assert.fail(e.getMessage());
} catch(SAXException e1){
Assert.fail(e1.getMessage());
}
}
最佳答案
您第一次尝试失败的可能原因之一是您使用的 DocumentBuilder
不支持命名空间。默认情况下,DocumentBuilderFactory
创建的解析器不会识别命名空间。在创建 DocumentBuilder
之前,您应该始终在 DocumentBuilderFactory
上启用命名空间支持。
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder parser = factory.newDocumentBuilder();
如果没有命名空间支持,由 DocumentBuilder
构建的 DOM 将包含缺少 localName
和 namespaceURI
值的 DOM Level 1 节点(请参阅DOM FAQ)。这些是 XML 模式 validator 在搜索元素声明时尝试从 DOM 读取的值。
关于java - cvc-elt.1.a : Cannot find the declaration of element 'ns0:Root' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34876820/