如何在一个xml文档中强制引用

时间:2017-04-24 21:51:53

标签: xml

您能告诉我如何在xsd文档中强制引用(通过xml文件)吗?

让我们考虑一下:

<city>
 <owners>
  <owner id="123">
    <name>John></name>
    ...
  </owner>
 </ownwers>
 <dogs>
  <dog>
    <idOwner>123</idOwner> <!-- that's ok because in this file there exists owner with id 123 -->
    ...
  </dog>
  <dog>
    <idOwner>1234</idOwner> <!-- that's not ok because in this file it doesn't exist owner with id 1234, so validation error should happen -->
    ...
  </dog>
 </dogs>
</city>
你可以帮我解决这个问题吗?我的意思是验证从狗到其所有者的正确引用(因此所有者ID必须存在于此xml文件中)。

1 个答案:

答案 0 :(得分:0)

我的建议是将idOwner作为dog的属性。

id的属性类型为xs:ID

idOwner的属性类型为xs:IDREF

See here for more information on the attribute type validity constraints.

示例...

<强> XSD

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
  <xs:element name="city">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="owners"/>
        <xs:element ref="dogs"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="owners">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" ref="owner"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="owner">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="name"/>
      </xs:sequence>
      <xs:attribute name="id" use="required" type="xs:ID"/>
    </xs:complexType>
  </xs:element>
  <xs:element name="name" type="xs:string"/>
  <xs:element name="dogs">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" ref="dog"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="dog">
    <xs:complexType>
      <xs:attribute name="idOwner" use="required" type="xs:IDREF"/>
    </xs:complexType>
  </xs:element>
</xs:schema>

<强> XML

<city xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="so.xsd">
    <owners>
        <owner id="ID-123">
            <name>John></name>
        </owner>
    </owners>
    <dogs>
        <dog idOwner="ID-123"/>
        <dog idOwner="ID-1234"/><!-- INVALID idOwner -->
    </dogs>
</city>