02.xsd
<?xml version="1.0" encoding="UTF-8"?>
<!-- xmlns(schema的默认命名空间不能修改,不过可以增加前缀 )
targetNamespace自己这个文档的命名空间,可以方便其他xml或者schema文件引用
xmlns:tns此处的名称和自己的名称空间的名称一致,但是增加了tns的前缀,此时如果要引用当前文件所创建的类型,需要加上tns的前缀
-->
<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>
<!-- sequence元素按顺序出现
all元素可不按顺序出现,但每个元素只能出现一次
minOccurs最小出现次数
maxOccurs最大出现次数
-->
<sequence>
<element name="book" maxOccurs="unbounded">
<complexType>
<!-- 定义book的元素 -->
<sequence minOccurs="1" maxOccurs="2">
<element name="tittle" type="string"></element>
<element name="content" type="string"></element>
<!-- 多个元素选取其中一个 -->
<choice>
<element name="author" type="string"></element>
<element name="authors">
<complexType>
<sequence>
<element name="author" type="string"></element>
</sequence>
</complexType>
</element>
</choice>
</sequence>
<!-- 定义book的属性(必须在sequence之后) -->
<!-- use="optional"表示可有可无
use="required"表示必须有
-->
<attribute name="id" type="int" use="required"></attribute>
</complexType>
</element>
</sequence>
</complexType>
</element>
</schema>
02.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- xmlns:xsi创建了一个可以引入其他schema文件的命名空间
xsi:schemaLocation引入其他命名空间
(xsi:noNamespaceSchemaLocation也可以通过这种方式(文件路径)引入schema文件)
-->
<book:books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:book="http://www.example.org/02"
xsi:schemaLocation="http://www.example.org/02">
<book:book id="1">
<book:tittle>java in action</book:tittle>
<book:content>java is good</book:content>
<book:authors>
<book:author>asdasd</book:author>
</book:authors>
</book:book>
</book:books>