目录

XSD 如何使用


XML 文档可以引用 DTD 或 XML 模式。


一个简单的 XML 文档

看一下这个名为 "note.xml" 的简单 XML 文档:

<?xml version="1.0"?>
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

DTD 文件

以下示例是一个名为 "note.dtd" 的 DTD 文件,它定义了上述 XML 文档的元素 ("note.xml"):

<!ELEMENT note (to, from, heading, body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>

第一行将 note 元素定义为具有四个子元素:"to, from, heading, body"。

第 2-5 行将 to、from、heading、body 元素定义为 "#PCDATA" 类型。


XML 模式

以下示例是一个名为 "note.xsd" 的 XML 架构文件,它定义了上述 XML 文档 ("note.xml") 的元素:

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="https://www.91xjr.com"
xmlns="https://www.91xjr.com"
elementFormDefault="qualified">

<xs:element name="note">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="to" type="xs:string"/>
      <xs:element name="from" type="xs:string"/>
      <xs:element name="heading" type="xs:string"/>
      <xs:element name="body" type="xs:string"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>

</xs:schema>

注释元素是复杂型因为它含有其他元素。其他元素(to、from、heading、body)是简单类型因为它们不包含其他元素。您将在接下来的章节中了解有关简单类型和复杂类型的更多信息。



对 DTD 的引用

此 XML 文档引用了 DTD:

<?xml version="1.0"?>

<!DOCTYPE note SYSTEM
"https://www.91xjr.com/xml/note.dtd">

<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

对 XML 模式的引用

此 XML 文档引用了 XML 架构:

<?xml version="1.0"?>

<note
xmlns="https://www.91xjr.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.91xjr.com/xml note.xsd">
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>