例子一
xsd文档
<?xml version="1.0" encoding="UTF-8"?>
<!-- xmlns:xs 显示 schema 中用到的元素和数据类型来自命名空间 -->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
<!-- targetNamespace 显示被此 schema 定义的元素被绑定到了命名空间 -->
targetNamespace="http://www.itheima.com/message"
<!-- 使用此 xsd 的实例文档必须遵守此文档的约束 -->
elementFormDefault="qualified">
<xs:element name="message">
<!-- 包含其他的子元素 -->
<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>
实例文档
<?xml version="1.0" encoding="UTF-8"?>
<!-- 此声明会告知schema 验证器,在此 XML 文档中使用的所有元素的约束都来源于 -->
<message xmlns="http://www.itheima.com/message"
<!-- 指定 XML Schema 实例命名空间 -->
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<!-- 供命名空间使用的 XML schema 的位置 -->
xsi:schemaLocation="http://www.itheima.com/message message.xsd">
<to>姚笛</to>
<from>文章</from>
<heading>旅游</heading>
<body>周一见</body>
</message>
例子二
xsd文档
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org/bookshelf"
elementFormDefault="qualified">
<!-- 根元素是bookshelf,包含子元素,所以是复杂类型 -->
<xs:element name="bookshelf">
<xs:complexType>
<!-- book出现1~n次 -->
<xs:sequence minOccurs="1" maxOccurs="unbounded">
<!-- book因为包含子元素和属性,所以也是复杂元素 -->
<xs:element name="book">
<!-- 元素要依次出现 -->
<xs:complexType>
<xs:sequence>
<!-- 其它元素都是简单元素 -->
<xs:element name="title" type="xs:string"/>
<xs:element name="author" type="xs:string"/>
<xs:element name="price" type="xs:positiveInteger"/>
</xs:sequence>
<!-- 属性要写在最后,这里表示属性必须 -->
<xs:attribute name="isbn" use="required"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
实例文档
<?xml version="1.0" encoding="UTF-8"?>
<p:bookshelf xmlns:p="http://www.example.org/bookshelf"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.example.org/bookshelf bookshelf.xsd ">
<p:book isbn="001">
<p:title>Java从入门到精通</p:title>
<p:author>高司令</p:author>
<p:price>99</p:price>
</p:book>
<p:book isbn="002">
<p:title>Java精通</p:title>
<p:author>高斯林</p:author>
<p:price>100</p:price>
</p:book>
</p:bookshelf>