xml – 为什么这个XDocument验证失败?

前端之家收集整理的这篇文章主要介绍了xml – 为什么这个XDocument验证失败?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
给定模式(匿名化,重命名关键点,其余部分省略):

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="inspec"
    targetNamespace="the_right_namespace"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
  <xs:element name="inspec">
    <xs:complexType>
      <xs:all>
        <xs:element name="a_scalar_property" type="xs:int"/>
        <xs:element name="a_collection_property">
          <xs:complexType>
            <snip>
          </xs:complexType>
        </xs:element>
        <xs:element name="another_collection_property">
          <xs:complexType>                
            <snip>
          </xs:complexType>
        </xs:element>                       
      </xs:all>
    </xs:complexType>
  </xs:element>
</xs:schema>

和实例(使用VB xml文字声明):

Dim xDocument = 
<x:inspec xmlns:x='the_right_namespace'>
<a_collection_property/>
<another_collection_property/>
</x:inspec>

验证失败并显示消息命名空间’the_right_namespace’中的元素’inspec’具有不完整的内容.期望的可能元素列表:’a_scalar_property’.

为什么?根据W3Schools的说法,所有元素都是:

“all元素指定子元素可以按任何顺序出现,并且每个子元素可以出现零次或一次.”

省略a_scalar_property与将其包括零次相同.为什么此文档无法验证?

并且不要说“发布完整代码”之类的内容 – 这不是我的IP,而且我已将其匿名化了,原因很简单.它没有什么其他的东西,我已经用这个最小的例子进行了测试,它给出了相同的结果.

解决方法

您需要为xs:all中的每个可选元素指定minOccurs =“0”:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="inspec"
    targetNamespace="the_right_namespace"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
    <xs:element name="inspec">
        <xs:complexType>
            <xs:all>
                <xs:element name="a_scalar_property" type="xs:int" minOccurs="0" />
                <xs:element name="a_collection_property" minOccurs="0">
                    <xs:complexType>
                        <!-- snip -->
                    </xs:complexType>
                </xs:element>
                <xs:element name="another_collection_property" minOccurs="0">
                    <xs:complexType>
                        <!-- snip -->
                    </xs:complexType>
                </xs:element>
            </xs:all>
        </xs:complexType>
    </xs:element>
</xs:schema>

猜你在找的XML相关文章