引言:
web 开发中,XML 会被用来描述和存储数据,而 HTML 会被用来显示数据。
我们对 XML 最合适的描述是,一个跨平台的、独立于软硬件的,信息存储和传输工具。
最近研究公司的框架webx3,发现里面的xml的配置与之前的webx2有明显的不同的,webx2采用的DTD的xml风格,而webx3采用的是xml schema的风格。今天简单罗列下这两者的区别、简单使用。
DTD 文件
下面这个例子是名为 "note.dtd" 的 DTD 文件,它对上面那个 XML 文档的元素进行了定义:
<!ELEMENT note (to, from, heading, body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT heading (#PCDATA)> <!ELEMENT body (#PCDATA)>第 1 行定义 note 元素有四个子元素:"to, from, heading, body"。
第 2-5 行定义了 to, from, heading, body 元素的类型是 "#PCDATA"。
对 DTD 的引用
此文件包含对 DTD 的引用:
<?xml version="1.0"?> <!DOCTYPE note SYSTEM "http://www.w3school.com.cn/dtd/note.dtd"> <note> <to>George</to> <from>John</from> <heading>Reminder</heading> <body>Don't forget the meeting!</body> </note>XML Schema
下面这个例子是一个名为 "note.xsd" 的 XML Schema 文件,它定义了上面那个 XML 文档的元素:
<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.w3school.com.cn" xmlns="http://www.w3school.com.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) 是简易类型,因为它们没有包含其他元素。
对 XML Schema 的引用
此文件包含对 XML Schema 的引用:
<?xml version="1.0"?> <note xmlns="http://www.w3school.com.cn" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3school.com.cn note.xsd"> <to>George</to> <from>John</from> <heading>Reminder</heading> <body>Don't forget the meeting!</body> </note>代码解释:
下面的片断:
xmlns="http://www.w3school.com.cn"规定了默认命名空间的声明。此声明会告知 schema 验证器,在此 XML 文档中使用的所有元素都被声明于 "http://www.w3school.com.cn" 这个命名空间。
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" XML Schema 实例命名空间。xsi:schemaLocation="http://www.w3school.com.cn note.xsd"可以使用 schemaLocation 属性。此属性有两个值。第一个值是需要使用的命名空间。第二个值是供命名空间使用的 XML schema 的位置.
更多详细内容可以参考:http://www.w3school.com.cn/schema/schema_schema.asp