声明
在编写XML文档时,需要先使用文档声明,声明XML文档的类型。
最简单的声明语法:
<?xml version="1.0" ?>
用encoding属性说明文档的字符编码:
<?xml version="1.0" encoding="GB2312" ?>
(xml文档以什么编码保存,就要以什么编码打开)
用standalone属性说明文档是否独立:
<?xml version="1.0" encoding="GB2312" standalone="yes" ?>
CDATA区域内的内容,XML解析程序不会处理,而是直接原封不动的输出。
语法:
<![CDATA[ 内容 ]]>
例如:
<![CDATA[
<itcast>
<br/>
</itcast>
]]>
引入约束
DTD约束
<!ELEMENT students (student*) >
<!ELEMENT student (name,age,sex)>
<!ELEMENT name (#PCDATA) >
<!ELEMENT age (#PCDATA) >
<!ELEMENT sex (#PCDATA) >
<!ATTLIST student number ID #REQUIRED>
引入DTD约束
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE students SYSTEM "students.dtd">
<students>
<student number="abc">
<name></name>
<age>apple</age>
<sex>pen</sex>
</student>
</students>
Schema约束
<?xml version="1.0"?>
<xsd:schema xmlns="http://www.itcast.cn/xml"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.itcast.cn/xml" elementFormDefault="qualified">
<xsd:element name="students" type="studentsType"/>
<xsd:complexType name="studentsType">
<xsd:sequence>
<xsd:element name="student" type="studentType" minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="studentType">
<xsd:sequence>
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="age" type="ageType" />
<xsd:element name="sex" type="sexType" />
</xsd:sequence>
<xsd:attribute name="number" type="numberType" use="required"/>
</xsd:complexType>
<xsd:simpleType name="sexType">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="male"/>
<xsd:enumeration value="female"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:simpleType name="ageType">
<xsd:restriction base="xsd:integer">
<xsd:minInclusive value="0"/>
<xsd:maxInclusive value="120"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:simpleType name="numberType">
<xsd:restriction base="xsd:string">
<xsd:pattern value="ITCAST_\d{4}"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>
引入Schema约束
<?xml version="1.0" encoding="utf-8" ?>
<!--
1.书写根元素(因为xsd文件的引入是在根元素上进行的)
2.在根元素上书写schemaLocation属性,填入命名空间,和xsd文件位置.(可以引入多个,没对之间用 空格/回车 隔开.)
3.为引入的xsd定义一个前缀.xmlns="http://www.itcast.cn/xml"
4.固定值. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-->
<students xmlns="http://www.itcast.cn/xml"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.itcast.cn/xml students.xsd" >
<student number="ITCAST_0001">
<name>tom</name>
<age>18</age>
<sex>male</sex>
</student>
</students>