XML Schema 如何使用 ?

XML 文档可对 DTD 或 XML Schema 进行引用

一个简单的 XML 文档

请看这个 note.xml 的 XML 文档

<?xml version="1.0"?>
    <note>
        <to>小明</to>
        <from>小红</from>
        <heading>短信</heading>
        <body>我想你了</body>
    </note>

DTD 文件

使用 DTD 对 note.xml 文档进行元素定义,可能如下

note.dtd

<!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 Schema

使用 XML Schema 对 note.xml 文档进行元素定义,可能如下

note.xsd

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="https://www.twle.cn" xmlns="http://www.twle.cn" 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 的引用

我们可以在 note.xml 中包含对 DTD 的引用

<?xml version="1.0"?>
<!DOCTYPE note SYSTEM "https://www.twle.cn/static/media/note_dtd.dtd" >
<note>
    <to>小明</to>
    <from>小红</from>
    <heading>短信</heading>
    <body>我想你了</body>
</note>

对 XML Schema 的引用

我们可以在 note.xml 中包含对 XML Schema 的引用

<?xml version="1.0"?>
<note xmlns="https://www.twle.cn" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://www.twle.cn note.xsd">
<note>
    <to>小明</to>
    <from>小红</from>
    <heading>短信</heading>
    <body>我想你了</body>
</note>
关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.