Schema对XML的约束

例子一
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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cyufeng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值