[英]Java XML parsing validation with schema is not enabled
Trying to parse XML with schema validation:尝试使用模式验证解析 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)
Schema:架构:
<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: 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>
But parsing without error.但是解析没有错误。 Is this the right way to enable schema validation while parsing DOM?这是在解析 DOM 时启用模式验证的正确方法吗?
http://java.sun.com
? http://java.sun.com
? very old domain?很老的域名?
You do not set Schema of DocumentBuilderFactory.您没有设置 DocumentBuilderFactory 的架构。 So DocumentBuilder can not validate.所以 DocumentBuilder 无法验证。 See javadoc for DocumentBuilderFactory setSchema method: * When a {@link Schema} is non-null, a parser will use a validator * created from it to validate documents before it passes information * down to the application.有关 DocumentBuilderFactory setSchema 方法的信息,请参阅 javadoc: * 当 {@link Schema} 为非空时,解析器将使用从它创建的验证器 * 在将信息传递给应用程序之前 * 来验证文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.