2012-05-09 116 views
0

我不知道如何标题我的问题。2个元素中的元素引用

我有包含以下元素的XSD

<xs:element name="abc"> 
    <xs:complexType> 
    <xs:element maxOccurs="unbounded" ref="ele1"/> 
    </xs:complexType> 
</xs:element> 

<xs:element name="xyz"> 
    <xs:complexType> 
    <xs:element maxOccurs="unbounded" ref="ele1"/> 
    </xs:complexType> 
</xs:element> 

<xs:element name="ele1"> 
    <xs:complexType> 
    <xs:attribute name="ID" type="xs:integer"/> 
    </xs:complexType> 
</xs:element> 

的问题是,对于元件xyzID是必需的,而对于abc它不是;我怎样才能在XSD中指定这个?

回答

0

假设ID是在“容器”重复内容的唯一标识符,那么你可以设置一个XS:键约束的XYZ是这样的:

<?xml version="1.0" encoding="utf-8" ?> 
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
    <xs:element name="abc"> 
     <xs:complexType> 
      <xs:sequence> 
       <xs:element maxOccurs="unbounded" ref="ele1"/> 
      </xs:sequence> 
     </xs:complexType> 
    </xs:element> 
    <xs:element name="xyz"> 
     <xs:complexType> 
      <xs:sequence> 
       <xs:element maxOccurs="unbounded" ref="ele1"/> 
      </xs:sequence> 
     </xs:complexType> 
     <xs:key name="PK_xyz"> 
      <xs:selector xpath="ele1"/> 
      <xs:field xpath="@ID"/> 
     </xs:key> 
    </xs:element> 
    <xs:element name="ele1"> 
     <xs:complexType> 
      <xs:attribute name="ID" type="xs:integer"/> 
     </xs:complexType> 
    </xs:element> 
</xs:schema> 

然后,无效的XML因为ID是失踪:

<?xml version="1.0" encoding="utf-8" standalone="yes"?> 
<!-- Sample XML generated by QTAssistant (http://www.paschidev.com) --> 
<xyz xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <ele1 ID="1"/> 
    <ele1 /> 
</xyz> 

错误消息:

Error occurred while loading [], line 5 position 3 
The identity constraint 'PK_xyz' validation has failed. Either a key is missing or the existing key has an empty node. 
Document3.xml is invalid. 

无效的,因为它是重复的(这是不利的一面,如果在独特上述假设不成立真):

<?xml version="1.0" encoding="utf-8" standalone="yes"?> 
<!-- Sample XML generated by QTAssistant (http://www.paschidev.com) --> 
<xyz xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <ele1 ID="1"/> 
    <ele1 ID="1"/> 
</xyz> 

错误:

Error occurred while loading [], line 5 position 3 
There is a duplicate key sequence '1' for the 'PK_xyz' key or unique identity constraint. 
Document3.xml is invalid. 

工作样本:

<?xml version="1.0" encoding="utf-8" standalone="yes"?> 
<!-- Sample XML generated by QTAssistant (http://www.paschidev.com) --> 
<xyz xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <ele1 ID="1"/> 
    <ele1 ID="2"/> 
</xyz>