XML Schema中的命名空间

本文深入解析了XMLSchema中的命名空间概念,包括默认命名空间、目标命名空间以及如何通过XMLschema定义不同命名空间的用法。同时,文章详细解释了如何声明schema的地址,并提供了创建目标XML文档的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在定义XML Schema时,通常我们会定义一些命名空间,例如:

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://www.liulutu.com/students/"
	targetNamespace="http://www.liulutu.com/students/">
	...
</schema>

 

(以下我的理解,错了别怪我)

其中:

  • xmlns:定义了默认的命令空间,也就是在当前schema中元素的默认命名空间。例如"schema"元素,由于没有给出一个名称空间前缀,所以默认的命名空间就是由"xmlns"给出的值http://www.w3.org/2001/XMLSchema
  • targetNamespace:目标元素的命名空间。所谓的目标元素是指符合这份schema定义的xml文档里的元素,例如:
    <?xml version="1.0" encoding="UTF-8"?>
    <schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://www.liulutu.com/students/"
    	targetNamespace="http://www.liulutu.com/students/">
    	<element name="students">
    		<complexType>
    			<sequence>
    				<element name="student" type="tns:StudentType" maxOccurs="unbounded" />
    			</sequence>
    		</complexType>
    	</element>
    	<simpleType name="SexType">
    		<restriction base="string">
    			<enumeration value="Male"></enumeration>
    			<enumeration value="Female"></enumeration>
    		</restriction>
    	</simpleType>
    
    	<complexType name="StudentType">
    		<attribute name="sex" type="tns:SexType"></attribute>
    		<attribute name="name" type="string"></attribute>
    	</complexType>
    </schema>
     对应的一份可能的目标xml内容为:
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <ns2:students xmlns:ns2="http://www.liulutu.com/students/">
        <student name="aaa" sex="Male"/>
        <student name="bbb" sex="Female"/>
    </ns2:students>
     那个这个targetNamespace就是用来定义students和student元素的名称空间
  • xmlns:tns:一份Xml schema里有时可能不止引用一个名称空间,因此就使用"xmlns:XXX"格式来定义一些其他的名称空间,然后引用些空间里的元素如下:"XXX:name"

要声明一个schema的地址,可以如下做:

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.w3school.com.cn note.xsd"

 其中schemaLocation的namespace需要是XMLSchema的名称空间,每个Location是一对值,其中前半部分代表这个schema的名称空间,后半部分值代码schema文件的路径

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值