dtd文件的作用就是约束xml文档,但是他不够牛逼,不够灵活。所以schema就孕育而生!!!
01.xsd //sechma文件的后缀是xsd
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org/01"
xmlns:tns="http://www.example.org/01"
elementFormDefault="qualified">
<element name="user">
<complexType>
<sequence>
<element name="id" type="int"/>
<element name="username" type="string"/>
<element name="born" type="date"/>
</sequence>
</complexType>
</element>
</schema>
<?xml version="1.0" encoding="UTF-8"?>
<user xmlns="http://www.example.org/01"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.example.org/01">
<id>1</id>
<username>zhangsan</username>
<born>1989-12-22</born>
</user>
写好之后引入xml文件
另外一种引入方式
下面写几个比较常用的几个参数
02.xsd
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/02"
xmlns:tns="http://www.example.org/02" elementFormDefault="qualified">
<element name="books">
<complexType>
<!-- maxOccurs表示最大出现次数 -->
<sequence maxOccurs="unbounded">
<element name="book">
<complexType>
<sequence minOccurs="1" maxOccurs="unbounded">
<element name="title" type="string" />
<element name="content" type="string" />
<choice>
<element name="author" type="string" />
<element name="authors">
<complexType>
<all><!-- 每个元素只能出现一次 -->
<element name="author" type="string"/>
</all>
</complexType>
</element>
</choice>
</sequence>
<attribute name="id" type="int" use="required"/>
</complexType>
</element>
</sequence>
</complexType>
</element>
</schema>
02.xml
<?xml version="1.0" encoding="UTF-8"?>
<book:books xmlns:book="http://www.example.org/02"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="02.xsd">
<book:book id="1">
<book:title>Java in action</book:title>
<book:content>Java is good</book:content>
<book:author>Bruce</book:author>
</book:book>
<book:book id="2">
<book:title>SOA in action</book:title>
<book:content>soa is difficult</book:content>
<book:authors>
<book:author>Jike</book:author>
</book:authors>
</book:book>
</book:books>
这里定义book的属性,一定要写在sequence之后