未启用带有模式的Java XML解析验证

问题描述 投票:0回答:1

[尝试通过模式验证解析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时启用架构验证的正确方法吗?

java xml validation xml-parsing schema
1个回答
0
投票

您未设置DocumentBuilderFactory的架构。因此DocumentBuilder无法验证。

© www.soinside.com 2019 - 2024. All rights reserved.