2012-07-01 109 views
5

鉴于架构(匿名,感兴趣的关键点被重命名,其余略):为什么此XDocument验证失败?

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

验证失败的:

<?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文本声明)消息The element 'inspec' in namespace 'the_right_namespace' has incomplete content. List of possible elements expected: 'a_scalar_property'.

为什么?根据W3Schools的all元素:

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

省略a_scalar_property与将其包括零次相同。为什么这个文件无法验证?

不要说'发布完整的代码' - 这不是我的知识产权,我有一个很好的理由匿名。除此之外没有其他的东西,我用这个最小的例子进行了测试,结果相同。

+0

相关:(我不是说他们必然是错在这种情况下)http://w3fools.com/ – JJJ

+0

谢谢 - 我还没有发现W3School可以很好地利用我自己,但是将它作为可能大家都听说过的参考 - 并且您真的希望页面上的第一句关于Xml Schema的基本片断是正确的! –

回答

6

你需要指定minOccurs="0"每一个可选元素在xs:all

<?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> 
+0

谢谢。似乎我不得不打扰 - 如果我仍然必须对每个元素进行注释,那么''的重点是什么?仍然可以解决这个问题。 –

+0

很高兴为您提供帮助。 'xs:all'只是解决了“以任何顺序”的一部分......当你需要“任何顺序”和“零个,一个或多个”时,你可能仍然会遇到欢乐。 – Filburt

2

要使元素可选,minOccurrs属性应该为0,即使在< all>组中也是如此。从阅读XML模式规范中获取它非常麻烦,但依赖w3schools不是一个好的选择。

+0

[MSDN上的文档](http://msdn.microsoft.com/zh-cn/library/ms256182)以同样的方式误导用户:*“允许组中的元素以任何顺序出现(或不出现)在包含元素中。“* – Filburt