XSD How To

创建于 2024-12-03 / 30
字体: [默认] [大] [更大]

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.w3ccoo.com"
xmlns="https://www.w3ccoo.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>

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



对DTD的引用

此XML文档引用了DTD:

<?xml version="1.0"?>

<!DOCTYPE note SYSTEM
"https://www.w3ccoo.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.w3ccoo.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.w3ccoo.com/xml note.xsd">
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

0 人点赞过