【问题标题】:Validation XML XSD Fails验证 XML XSD 失败
【发布时间】:2010-11-02 17:04:54
【问题描述】:

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.

【问题讨论】:

    标签: java xml validation xsd


    【解决方案1】:

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

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

    【讨论】:

    • 您是否将 p: 添加到所有元素中?它需要无处不在,而不仅仅是根目录。这就是 targetNamespace="xml.netbeans.org/schema/Person" 的意思。
    • +1,但从技术上讲,它是 targetNamespace 和 elementFormDefault="qualified" 的组合,要求所有节点都是命名空间限定的。如果 elementFormDefault 设置为“unqualified”(或未设置),则只有全局声明的元素需要前缀限定(在这种情况下只有“root”)。
    【解决方案2】:

    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"));
        }
    }
    

    【讨论】:

      【解决方案3】:

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

      要么

      <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>
      

      【讨论】:

        猜你喜欢
        • 2019-06-23
        • 2019-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-09
        • 2015-02-16
        • 1970-01-01
        • 2012-10-16
        相关资源
        最近更新 更多