gpt4 book ai didi

java - XML 验证错误,未找到元素(我认为即使元素存在并且架构和 xml 已正确加载)

转载 作者:行者123 更新时间:2023-12-01 15:20:19 24 4
gpt4 key购买 nike

我正在尝试使用以下代码块根据 XML 架构验证简单的 XML 文件。我遇到异常

org.xml.sax.SAXParseException: cvc-elt.1: 
Cannot find the declaration of element 'Applications'

并且想知道是否有人知道为什么会这样。 (当我尝试查看模式加载后的内容时,我看到一堆语法对象或类似的东西,没有任何迹象表明模式已正确加载。可能是这样吗?如果我尝试加载具有不存在文件名的架构,它给我一个文件未找到异常...所以我得到它是在给出正确的文件名时找到正确的架构)

public void getPriceSummaryInfo(){
Document doc = null;
try {
File fXmlFile = new File("testXML.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(fXmlFile);
}
catch (Exception e) {
e.printStackTrace();
}

try {
Schema schema = getSchema("testSchema.xsd");
Validator validator = schema.newValidator();
validator.validate(new DOMSource(doc));
}
catch (Exception e) {
e.printStackTrace();
}
}

private Schema getSchema (String xsdPath) throws Exception {
assert xsdPath != null : "XML schema path is null.";
SchemaFactory fact =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

Schema schema;
try {
schema = fact.newSchema(new StreamSource(new File(xsdPath)));
}
catch (SAXException e) {
throw new Exception(
"Unable to find target schema to validate XML.", e);
}
return schema;
}

xml 和 xsd 文件是:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.randomthing.com"
xmlns="http://www.randomthing.com"
elementFormDefault="qualified">

<xsd:element name="Applications">
<xsd:complexType>
<xsd:sequence>
<xsd:element ref="Application" minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>

<xsd:element name="Application">
<xsd:annotation>
<xsd:documentation>
blah
</xsd:documentation>
</xsd:annotation>
<xsd:complexType>
<xsd:attribute name="id" type="xsd:long" use="required"/>
<xsd:attribute name="name" type="xsd:string" use="required"/>
<xsd:attribute name="order" type="xsd:long" use="required"/>
</xsd:complexType>
</xsd:element>
</xsd:schema>



<?xml version="1.0" encoding="UTF-8"?>
<Applications xmlns ="http://www.randomthing.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.randomthing.com testSchema.xsd">

<Application id="3" name="Blah" order="2">
</Application>
</Applications>

非常感谢任何指点!谢谢

最佳答案

您应该使用 namespace 解析文档,您会在加载时丢失它们。

dbFactory.setNamespaceAware(true);

关于java - XML 验证错误,未找到元素(我认为即使元素存在并且架构和 xml 已正确加载),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11024541/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com