当前位置: java基础教程 > 24-xml > 阅读正文

xml 约束

2021.1.7.   537 次   1883字

约束的作用:限制写的标签,以便让程序能够读取

约束的分类:

  • DTD:一种简单的约束技术
  • Schema:一种复杂的约束技术

1.DTD 约束

1.引入DTD文件(文件后缀 .dtd)

1.内部 DTD :直接将约束写在文件内

2.外部约束

  • 本地:<!DOCTYPE 根标签名称 SYSTEM “DTD文件位置”>
  • 网络:<!DOCTYPE 根标签名称 PUBLIC “DTD文件名” “DTD文件位置”>
2.阅读与编写DTD,这里给一个示例

规定根标签是 students,子标签是 student,student里有 name, age, sex

<!ELEMENT students (student*) >
<!ELEMENT student (name,age,sex)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT age (#PCDATA)>
<!ELEMENT sex (#PCDATA)>
<!ATTLIST student number ID #REQUIRED>

2.Schema 约束

1.引入Schema文件(文件后缀 .xsd)

1.首先书写根标签,在根标签中,填写xsi 前缀,该取值有多种,这里写一种

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

2.引入 xsd 文件命名空间,这里的location就是文件命名空间

xsi:schemaLocation="http://www.52dixiaowo.com/xml  student.xsd"

3为每一个 xsd 声明一个约束前缀,作为表示,例如 a 前缀(默认为空)

xmlns:a="http://www.52dixiaowo.com/xml"
2.阅读与编写 xsd

仍然是 student 约束,根标签 students,子标签student,属性name, age, sex

<?xml version="1.0"?>
<xsd:schema xmlns="http://www.52dixiaowo.com/xml"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        targetNamespace="http://www.52dixiaowo.coms/xml" elementFormDefault="qualified">
    <xsd:element name="students" type="studentsType"/>
    <xsd:complexType name="studentsType">
        <xsd:sequence>
            <xsd:element name="student" type="studentType" minOccurs="0" maxOccurs="unbounded"/>
        </xsd:sequence>
    </xsd:complexType>
    <xsd:complexType name="studentType">
        <xsd:sequence>
            <xsd:element name="name" type="xsd:string"/>
            <xsd:element name="age" type="ageType" />
            <xsd:element name="sex" type="sexType" />
        </xsd:sequence>
        <xsd:attribute name="number" type="numberType" use="required"/>
    </xsd:complexType>
    <xsd:simpleType name="sexType">
        <xsd:restriction base="xsd:string">
            <xsd:enumeration value="male"/>
            <xsd:enumeration value="female"/>
        </xsd:restriction>
    </xsd:simpleType>
    <xsd:simpleType name="ageType">
        <xsd:restriction base="xsd:integer">
            <xsd:minInclusive value="0"/>
            <xsd:maxInclusive value="256"/>
        </xsd:restriction>
    </xsd:simpleType>
    <xsd:simpleType name="numberType">
        <xsd:restriction base="xsd:string">
            <xsd:pattern value="heima_\d{4}"/>
        </xsd:restriction>
    </xsd:simpleType>
</xsd:schema> 

本篇完,还有疑问?

加入QQ交流群:11500065636 IT 技术交流群