验证XML XSD失败

时间:2010-11-02 17:04:54

标签: java xml validation xsd

XSD

<?xml version="1.0" encoding="windows-1252"?>

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://xml.netbeans.org/schema/Person"
    xmlns:tns="http://xml.netbeans.org/schema/Person"
    elementFormDefault="qualified">
    <xsd:element name="root">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="persons">
                    <xsd:complexType>
                        <xsd:sequence>
                            <xsd:element name="person" maxOccurs="unbounded">
                                <xsd:complexType>
                                    <xsd:sequence>
                                        <xsd:element name="name" type="xsd:string"></xsd:element>
                                        <xsd:element name="age" type="xsd:int"></xsd:element>
                                        <xsd:element name="address" type="xsd:string"></xsd:element>
                                    </xsd:sequence>
                                </xsd:complexType>
                            </xsd:element>
                        </xsd:sequence>
                    </xsd:complexType>
                </xsd:element>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
</xsd:schema>    

XML文件

<root>
  <persons>
    <person>
      <name>name1</name>
      <age>1</age>
      <address>abc abc abc1</address>
    </person>
    <person>
      <name>name2</name>
      <age>2</age>
      <address>abc abc abc2</address>
    </person>
    <person>
      <name>name2</name>
      <age>3</age>
      <address>abc abc abc3</address>
    </person>
  </persons>
</root>  

针对XSD验证XML的代码:

 public static String validateXMLwithXSD(String xmlFile, String xsdFile) {
        String result = "SUCCESS";
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            System.out.println("DocumentBuilderFactory: " + factory.getClass().getName());
            factory.setNamespaceAware(true);
            factory.setValidating(true);
            factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
            // Specify our own schema - this overrides the schemaLocation in the xml file
            factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", "d:\\person.xsd");
            DocumentBuilder builder = factory.newDocumentBuilder();
            builder.setErrorHandler(new SimpleErrorHandler());
            Document document = builder.parse(xmlFile);
            Node rootNode = document.getFirstChild();
            System.out.println("Root node: " + rootNode.getNodeName());
        } catch (Exception ex) {
            System.out.println("--------------------");
            result = "FAILURE:" + ex.getMessage();
            ex.printStackTrace();
        }catch (Error ex) {
            System.out.println("--------------------");
            result = "FAILURE:" + ex.getMessage();
            ex.printStackTrace();
        }

        return result;

    }

它抛出

DocumentBuilderFactory: com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl
org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'root'.
        at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)  

更新: 在戴维斯回答之后

[exec:exec]
DocumentBuilderFactory: com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl
org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'persons'. One of '{"http://xml.netbeans.org/schema/Person":persons}' is expected.
        at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)  


error: cvc-complex-type.2.4.a: Invalid content was found starting with element 'persons'. One of '{"http://xml.netbeans.org/schema/Person":persons}' is expected.

3 个答案:

答案 0 :(得分:3)

架构的目标命名空间是http://xml.netbeans.org/schema/Person,但示例xml根本不在命名空间中。可能你想要这样的东西:

<p:root xmlns:p="http://xml.netbeans.org/schema/Person">
...
</p:root>

答案 1 :(得分:1)

正如大卫所说,但你必须将名称空间添加到所有标签。

无论

<p:root xmlns:p="http://xml.netbeans.org/schema/Person">
  <p:persons>
    <p:person>
     ...
    </p:person>
  <p:persons>
</p:root>

或者

<root xmlns="http://xml.netbeans.org/schema/Person">
   <persons>
      ...
   </persons>
</root>

答案 2 :(得分:1)

David's answer关于命名空间限定是正确的,您的XML应如下所示:

<root xmlns="http://xml.netbeans.org/schema/Person">
  <persons>
    <person>
      <name>name1</name>
      <age>1</age>
      <address>abc abc abc1</address>
    </person>
    <person>
      <name>name2</name>
      <age>2</age>
      <address>abc abc abc2</address>
    </person>
    <person>
      <name>name2</name>
      <age>3</age>
      <address>abc abc abc3</address>
    </person>
  </persons>
</root> 

即使使用正确的XML架构,如果解析器无法正确查找XML架构,我也会看到该错误。您使用的方法已经很老了。如果您使用的是Java SE 5或更高版本,则可以在解析XML文档时使用以下代码执行验证:

import java.io.File;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.validation.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
        Schema schema = sf.newSchema(new File("person.xsd")); 

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setSchema(schema);
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.parse(new File("person.xml"));
    }
}