为了使XML文档规范化,对XML文档的书写进行约束
XML DTD
XML文档(test.xml)
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE books SYSTEM "books.dtd">
<books>
<book>
<name>java</name>
<price>$16</price>
</book>
</books>
DTD约束文档(books.dtd)
<!ELEMENT books (book)>
<!ELEMENT book (name,price)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT price (#PCDATA)>
<!ELEMENT book (name,price)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT price (#PCDATA)>
也可以写在一起:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE users [
<!ELEMENT users (user*)>
<!ELEMENT user (id,username,password,email,birthday)>
<!ELEMENT id (#PCDATA)>
<!ELEMENT username (#PCDATA)>
<!ELEMENT password (#PCDATA)>
<!ELEMENT email (#PCDATA)>
<!ELEMENT birthday (#PCDATA)>
]>
<users>
<!DOCTYPE users [
<!ELEMENT users (user*)>
<!ELEMENT user (id,username,password,email,birthday)>
<!ELEMENT id (#PCDATA)>
<!ELEMENT username (#PCDATA)>
<!ELEMENT password (#PCDATA)>
<!ELEMENT email (#PCDATA)>
<!ELEMENT birthday (#PCDATA)>
]>
<users>
<user>
<id>1</id>
<username>1</username>
<password>1</password>
<email>1</email>
</user>
</users>
<id>1</id>
<username>1</username>
<password>1</password>
<email>1</email>
</user>
</users>
引入外部DTD
本地DTD<!DOCTYPE root-element SYSTEM "filename">
公共DTD<!DOCTYPE root-element PUBLIC "DTD-NAME" "URL">
元素声明
<!ELEMENT element-name category>
或
<!ELEMENT element-name (element-content)>
或
<!ELEMENT element-name (element-content)>
符号使用
category
属性定义
实体定义
实体定义有点像C中的宏定义
例:
定义实体:<!ENTITY string “Hello World!”>
使用实体:&string;
XML Schema
xml Schema使用预先定义好的元素和属性开发的,其本身就是XML文档(这与DTD不同),通过Schema再来规定XML实例文档。
由于一个XML实例文档可以引入多个Schema,为了避免元素重名问题,每个Schema都应有一个名称空间(这里使用URI来区分)。
XML文档(test.xml)
@H_599_301@<?xml version="1.0" encoding="utf-8"
?>
<books
xmlns="http://www.dy-pc.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.dy-pc.com test.xsd"
>
<book>
<name>java</name>
<price>$16</price>
</book>
</books>
约束文档(test.xsd)
@H_599_301@<?xml version="1.0" encoding="utf-8" ?>
@H_599_301@<schema xmlns="http://www.w3.org/2001/XMLSchema"
@H_599_301@targetNameSpace="http://www.dy-pc.com"
@H_599_301@elementFormDefault = "qualified"
@H_599_301@>
@H_599_301@<element name="books">
@H_599_301@<complexType>
@H_599_301@<sequence>
@H_599_301@<element name="book">
@H_599_301@<squence>
@H_599_301@<element name="name" type="string" />
@H_599_301@<element name="price" type="double" />
@H_599_301@</squence>
@H_599_301@</element>
@H_599_301@</sequence>
@H_599_301@</complexType>
@H_599_301@</element>
@H_599_301@</schema>
原文链接:https://www.f2er.com/xml/295720.html