xml的schema约束(Java)

1.schema约束

*dtd语法:<!ELEMENT 元素名称 约束>

  schema符合xml的语法,是xml语句。

  一个xml文件中可以有多个schema,多个schema使用名称空间来区分(类似于java中的包),而一个xml文件中只能有提个dtd。

  dtd中有PCDATA类型,而在schema中支持多种数据类型,比如,年龄只能是一个整数,在schema中可以直接定义一个整数类型。

  schema语法更加复杂,目前不能代替dtd。

person.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.example.org/schema"
xsi:schemaLocation="http://www.example.org/schema schema.xsd" id1="123">
     <name>宝娟</name>
     <age>20</age>
     <school>**大学**</school>  
</person>

<!--
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance":表示是一个被约束文件
xmlns="http://www.example.org/schema":约束文件里的targetNamespace
:xsi是一个随便起的别名,为了区分开二者同名。
xsi:schemaLocation="http://www.example.org/schema schema.xsd">:
targetNamespace 空格  约束文档的路径
 -->

2.schema快速入门

*创建一个schema文件,它的后缀名为 .xsd

schema.xsd

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.example.org/schema"
    xmlns:tns="http://www.example.org/schema"
    elementFormDefault="qualified">
    <element name="person">
        <complexType>
            <sequence>
                <element name="name" type="string" maxOccurs="unbounded"></element>
                <element name="age" type="int"></element>
                <element name="school" type="string"></element>
            </sequence>
            <attribute name="id1" type="int" use="required"></attribute>
        </complexType>
    </element>
</schema>

<!-- 约束
在schema文件里:
属性:xmlns="http://www.w3.org/2001/XMLSchema"表示当前xml文件是一个约束文件
targetNamespace="http://www.example.org/schema":使用schema文件时,直接通过这个地址引入约束文件。
elementFormDefault="qualified":表示质量良好的。
1.看xml中有多少个元素,就对应在schema文件中有多少个<element></element>
2.判断简单元素/复杂元素
* 复杂元素:
<element name="person">
        <complexType>
            <sequence>
                         子元素
            </sequence>
        </complexType>
</element>
* 简单元素:写在
<sequence>
       简单元素
</sequence>

**    <sequence>表示元素出现的次序必须一致
<all>:元素只能出现一次
<choice>:元素只能出现其中的一个
maxOccurs="unbounded":表示元素出现的次数
<any></any>:表示任意元素   **

属性约束:只能用于复杂元素,所放的位置如下:
</sequence>
            <attribute name="id1" type="int" use="required"></attribute>
</complexType>
*****以上所有语句,属性type之前必须要有"空格"。如果没有的话,会报错。
*****多个schema约束具体可以去查看文档。
 -->

原文地址:https://www.cnblogs.com/aasu/p/9128548.html