为什么XSD验证期望{element}使用大括号而不仅仅是元素?

时间:2017-10-15 00:09:40

标签: xml xsd xsd-validation xml-validation

当我尝试针对以下XSD验证以下XML时,我收到以下错误:

  

cvc-complex-type.2.4.a:找到以元素>'personal'开头的无效内容。其中一个'{personal} expected。

XML

<main xmlns = "http://www.example.com"
      xmlns:xsi = "https://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation = "main.xsd">
  <personal>
    <full-name>John Smith</full-name>
    <contact>
      <street-address>12345 Example Street</street-address>
      <city>Somewhere</city>
      <state>EX</state>
      <postal-code>111 111</postal-code>
      <phone>123 456 7890</phone>
      <email>myemail@example.com</email>
    </contact>
  </personal>
</main>  

XSD

<xsd:schema xmlns:xsd = "http://www.w3.org/2001/XMLSchema"
            targetNamespace = "http://www.example.com"
            xmlns = "http://www.example.com">
  <xsd:element name = "main" type = "main-type"/>

  <xsd:complexType name = "main-type">
    <xsd:all>
      <xsd:element name = "personal" type = "personal-type"/>
    </xsd:all>
  </xsd:complexType>

  <xsd:complexType name = "personal-type">
    <xsd:all>
      <xsd:element name = "full-name" type = "xsd:string" 
                   minOccurs = "1"/>
      <xsd:element name = "contact" type = "contact-type" 
                   minOccurs = "1"/>
    </xsd:all>
  </xsd:complexType>

  <!--Different xsd:strings for contact information in contact-type-->
  <xsd:complexType name = "contact-type">
    <xsd:all>
      <xsd:element name = "street-address" type = "xsd:string"/>
      <xsd:element name = "city" type = "xsd:string"/>
      <xsd:element name = "state" type = "xsd:string"/>
      <xsd:element name = "postal-code" type = "xsd:string"/>
      <xsd:element name = "phone" type = "xsd:string"/>
      <xsd:element name = "email" type = "xsd:string"/>
    </xsd:all>
  </xsd:complexType>
</xsd:schema>

问题是什么?我该如何解决?

1 个答案:

答案 0 :(得分:3)

您发布的XML在发布的错误消息之前有两个初步问题:

  1. 更改

    xmlns:xsi = "https://www.w3.org/2001/XMLSchema-instance"
    

    xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
    
  2. 更改

    xsi:schemaLocation = "main.xsd"
    

    xsi:schemaLocation = "http://www.example.com main.xsd"
    
  3. 现在,您发布的XML和XSD实际上将处于显示已发布问题的状态:

      

    [错误] main.xml:4:13:cvc-complex-type.2.4.a:内容无效   从element&#39; personal&#39;开始。其中一个{个人}&#39;是   预期

    说明:此错误告诉您personal根据您的XSD预计不在命名空间中; {中的}One of '{personal}' is expected表示这一点。

    您可能认为,因为您的XSD声明targetNamespace="http://www.example.com"所有组件都放在http://www.example.com命名空间中。对于本地声明的组件,情况并非如此,但 除非您设置elementFormDefault="qualified" - 默认值为unqualified

    默认情况下,本地声明的元素位于 no namespace

    因此,请进行最后一次更改:添加

    elementFormDefault="qualified"
    

    xsd:schema元素,然后您的XML对XSD有效。

    另见 this answer about what elementFormDefault means