1.使用Altova XMLSpy新建一个xsd文件
文件默认样式为:
2.修改xsd文件内容
根据正确的xsd文件格式编辑xsd文件内容,Altova XMLSpy会对xsd文件格式进行验证,格式验证正确后保存为contacts.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:element name="通讯录">
<xs:annotation>
<xs:documentation>通讯录</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element ref="记录" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="记录">
<xs:complexType>
<xs:sequence><!--该元素必需按顺序包含下列 3 个元素-->
<xs:element ref="姓名"/>
<xs:element ref="关系"/>
<xs:element ref="电话"/>
</xs:sequence>
<xs:attribute name="编号" use="required">
<xs:simpleType>
<xs:restriction base="xs:decimal"/>
</xs:simpleType>
<!--说明编号属性的类型:必须为整数-->
</xs:attribute>
</xs:complexType>
</xs:element>
<xs:element name="姓名">
<xs:simpleType>
<xs:restriction base="xs:string"/>
</xs:simpleType>
<!--补充姓名的类型:字符串-->
</xs:element>
<xs:element name="关系">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="朋友"/>
<xs:enumeration value="同事"/>
<xs:enumeration value="亲属"/>
<xs:enumeration value="一般"/>
</xs:restriction>
</xs:simpleType>
<!--补充关系的类型:必须为朋友、同事、亲属、一般中的一种,不能重复-->
</xs:element>
<xs:element name="电话">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="\d{3}-\d{8}"></xs:pattern>
</xs:restriction>
</xs:simpleType>
<!--补充电话的类型:按照形式“区号-号码”表示,其中区号占3位,号码占8位-->
</xs:element>
</xs:schema>
3.新建一个XML文件
4.为XML文件,引入contacts.xsd文件
5.生成被contacts.xsd约束的xml形式,填写值会被定义xsd文件约束
6.填写正确的xml形式才能进行保存,否则会校验不能通过
(1)校验失败
(2)校验成功
注意:
命名空间路径为:http://www.w3.org/2001/XMLSchema-instance
xsi:noNamespaceSchemaLocation="file:///C:/Users/Administrator/Desktop/contacts.xsd"指定了xsd文件的本地路径
<?xml version="1.0" encoding="UTF-8"?>
<通讯录 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="file:///C:/Users/Administrator/Desktop/contacts.xsd">
<记录 编号="01">
<姓名>张三</姓名>
<关系>一般</关系>
<电话>010-12345678</电话>
</记录>
<记录 编号="02">
<姓名>李四</姓名>
<关系>同事</关系>
<电话>010-12345678</电话>
</记录>
</通讯录>