XSD关联是通过ID引用而不是值?

时间:2018-07-12 08:46:21

标签: xml xsd xsd-validation xml-validation

我是XML架构定义的新手。请查看我的XSD:

Author.xsd:

<?xml version="1.0" encoding="utf-8"?>

<xs:schema elementFormDefault="qualified" 
targetNamespace="http://NamespaceTest.com/AuthorType"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element id="author" name="author" type="AuthorType"/>
<xs:complexType name="AuthorType">
    <xs:complexContent>
        <xs:extension base="PersonType">
            <xs:sequence>

            </xs:sequence>
            <xs:attribute name="id" type="xs:int" use="required"/>
        </xs:extension>
    </xs:complexContent>
</xs:complexType>
</xs:schema>

Book.xsd:

<?xml version="1.0" encoding="utf-8"?>

<xs:schema elementFormDefault="qualified"
targetNamespace="http://NamespaceTest.com/BookType"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:include schemaLocation="http://NamespaceTest.com/AuthorType"/>
<xs:include schemaLocation="http://NamespaceTest.com/ReaderType"/>
<xs:complexType name="BookType">
    <xs:sequence>
        <xs:element name="name" type="xs:string"/>
        <xs:element name="date" type="xs:string"/>
        <xs:element name="author" type="AuthorType" />
        <xs:element name="reader" type="ReaderType"/>
    </xs:sequence>
    <xs:attribute name="id" type="xs:int"/>
</xs:complexType>
</xs:schema>

BookType中,我想要作者id和读者id。在这种状态下,当我仅需要它们的ID时,我会提供完整的authorreader详细信息。

1 个答案:

答案 0 :(得分:0)

它有助于查看XML级别。

当前,您通过在book元素中包含一个author元素来将authorbook进行关联:

<book>
  <name>John</name>
  <date>2018-07-12</date>
  <author id="a1">
    <!-- author elements -->
  </author>
</book>

相反,您只想通过其ID引用author

<book>
  <name>John</name>
  <date>2018-07-12</date>
  <author idref="a1"/>
</book>

这是基本XML标识符和标识符引用(在XSD中:xs:IDxs:IDREF)支持的方案。将您的id属性更改为xs:ID类型,并将您的引荐属性更改为xs:IDREF类型。

注释:

  • XML ID必须以namestart字符(不包括数字)开头。
  • 或者,您可以使用xs:typexs:token作为ID并强制执行 通过xs:unique来实现唯一性。
  • XSD还提供了xs:key / xs:keyref作为身份参考的一种更灵活的选择, 传统的XML / DTD id / idref机制。
相关问题