gpt4 book ai didi

未启用使用架构的 Java XML 解析验证

转载 作者:行者123 更新时间:2023-12-01 17:39:31 25 4
gpt4 key购买 nike

尝试使用架构验证来解析 XML:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setValidating(true);
dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
"http://www.w3.org/2001/XMLSchema");

DocumentBuilder db = dbf.newDocumentBuilder();
db.parse(xmlFile)

架构:

<xsd:schema targetNamespace="http://xmlns.example.com/xml/example"
xmlns:orm="http://xmlns.example.com/xml/example"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified"
attributeFormDefault="unqualified"
version="1.0">
<xsd:element name="book">
<xsd:complexType>

<xsd:sequence>
<xsd:element name="name" type="xsd:string"
minOccurs="1"/>
<xsd:element name="author" type="xsd:string"
minOccurs="1"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>

XML:

<book xmlns="http://xmlns.example.com/xml/example"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.example.com/xml/example http://xmlns.example.com/xml/example/example.xsd">
<name>Foo</name>
<author>Bar</author>
<hello>world</hello> <----INVALID
</book>

但是解析没有错误。这是在解析 DOM 时启用架构验证的正确方法吗?

http://java.sun.com?非常旧的域名?

最佳答案

您没有设置DocumentBuilderFactory的Schema。所以DocumentBuilder无法验证。有关 DocumentBuilderFactory setSchema 方法,请参阅 javadoc: * 当{@link Schema}非空时,解析器将使用 validator * 从它创建以在传递信息之前验证文档 * 深入到应用程序。

关于未启用使用架构的 Java XML 解析验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60983447/

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