XML学习之--Schema

schema约束

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

    schema符合xml的语法

xml语句:

  1.      一个xml中可以有多个schema,多个schema使用名称空间区分(类似于java包名)
  2.     dtd里面有PCDATA类型,但是在schema里面可以支持更多的数据类型
  3.     比如 年龄 只能是整数,在schema可以直接定义一个整数类型
  4.     schema语法更加复杂,schema目前不能替代dtd

schema建立

schema文件 后缀名是 .xsd

根节点 <schema xmlns="http://www.w3.org/2001/XMLSchema" 
              targetNamespace="http://www.example.org/person" 

              elementFormDefault="qualified">

在schema文件里面

    属性  xmlns="http://www.w3.org/2001/XMLSchema"            (表示当前xml文件是一个约束文件)
            targetNamespace="http://www.example.org/person"  (使用schema约束文件,直接通过这个地址引入约束文件)

            elementFormDefault="qualified"                                    (表示质量良好)

schema文件的写法步骤

看xml中有多少个元素   <element>
看简单元素和复杂元素
    如果复杂元素
    <complexType>
        <sequence>
    子元素
</sequence>

    </complexType>

简单元素,写在复杂元素的

<element name="person">
<complexType>
<sequence>
<element name="name" type="string"></element>
<element name="age" type="int"></element>
</sequence>
</complexType>
</element>


在被约束文件(XML)里面引入约束文件
<person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.example.org/person"
xsi:schemaLocation="www.example.org/person person.xsd">


xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"              表示xml是一个被约束文件
xmlns="http://www.itcast.cn/20151111"                                             是约束文档里面 targetNamespace
xsi:schemaLocation="http://www.itcast.cn/20151111 1.xsd">           targetNamespace空格 约束文档的地址路径
                                                                                 

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

Schema也可以约束属性

写在复杂元素里面,写在 </complexType>之前
    <attribute name="id1" type="int" use="required"></attribute>
         name: 属性名称
        type:属性类型 int stirng

        use:属性是否必须出现 required

另外在XML中在引入多个xsd时要起别名。

<company xmlns = "http://www.example.org/company"

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

xsi:schemaLocation="http://www.example.org/company company.xsd

        http://www.example.org/department department.xsd" 

>


在XML中这样用<dept:name>100</dept:name>

猜你喜欢

转载自blog.csdn.net/hare_you/article/details/79966528