一些巨大的基本错误——“找不到元素 X”
我的 xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<credits>
</credits>
我的模式
<?xml version="1.0" encoding="UTF-8" ?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="credits">
</xsd:element>
</xsd:schema>
它说“SaxParseException:找不到元素'credits'的声明”
什么?! :P 这怎么可能?这里绝对令人困惑。谷歌搜索了几个小时还没有任何结果。
谢谢!
SchemaFactory schemaFactory = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI );
Schema schemaXSD = schemaFactory.newSchema( new File ( "test.xsd" ) );
Validator v = schemaXSD.newValidator();
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = parser.parse( new File( "test.xml" ) );
document.toString();
DOMSource testSource = new DOMSource(document);
v.validate( testSource );
编辑: 找到了解决方案。谷歌终于有了成果。 :P 我必须添加
factory.setNamespaceAware(true);
到我的 DocumentBuilderFactory 对象。 :D
My xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<credits>
</credits>
My schema
<?xml version="1.0" encoding="UTF-8" ?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="credits">
</xsd:element>
</xsd:schema>
And it says "SaxParseException: cannot find declaration of element 'credits'"
What?! :P How is that possible? Absolutely confounded here. Been googling for hours nothing yet.
Thanks SO!
SchemaFactory schemaFactory = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI );
Schema schemaXSD = schemaFactory.newSchema( new File ( "test.xsd" ) );
Validator v = schemaXSD.newValidator();
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = parser.parse( new File( "test.xml" ) );
document.toString();
DOMSource testSource = new DOMSource(document);
v.validate( testSource );
EDIT:
Found the solution. Google finally yielded something. :P
I had to add
factory.setNamespaceAware(true);
to my DocumentBuilderFactory object. :D
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
意味着 test.xml 没有
credits
元素。如果可以接受,请设置minOccurs="0"
means that the test.xml doesn't have a
credits
element. If this is acceptable, setminOccurs="0"