我对xml命名空间有几个疑问,我将用这三段代码来解释:
1 - 非常简单的 XML 模式:
<?xml version="1.0" encoding="US-ASCII"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:tns="http://www.library.com"
targetNamespace="http://www.library.com"
elementFormDefault="qualified"
attributeFormDefault="unqualified">
<element name="Book" type="tns:BookType" />
<complexType name="BookType">
<sequence>
<element name="Title" type="string" />
<element name="Author" type="string" />
</sequence>
</complexType>
</schema>
2 - 使用新创建的 xml 架构的 XML:
<?xml version="1.0" encoding="US-ASCII"?>
<Book xmlns:xsi="http://www.wc3.org/2001XMLSchema-instance"
xsi:schemaLocation="http://www.library.com ex9.xsd"
xmlns="http://www.library.com">
<Title>Scherlock Holmes</Title>
Author>Arthur Conan Doyle</Author>
</Book>
3 - 另一个与上面两个没有关系的片段代码:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
....
</beans>
问题是:
- 为什么我们总是像这样声明命名空间 xmlns="http://www.w3.org/2001/XMLSchema" 和xmlns:xsi="http://www.wc3.org/2001/XMLSchema-instance" 但没有给出这些的 schemaLocation?
- XML 解析器如何知道(例如为了验证)
xmlns="http://www.w3.org/2001/XMLSchema" 定义类似
<attribute>
的元素,<complexType>
,<sequence>
等等? - 阅读许多帖子后,我了解到命名空间及其 URI, 基本上没有任何意义,它们只是用来避免名字 矛盾的。但我还读到,如果你声明 xmlns="http://www.w3.org/2001/XMLSchema" 命名空间错误 XML 文件将无效,为什么?
- 为什么在最后一个代码片段中总是没有给出 schemaLocation <强> http://www.w3.org/2001/XMLSchema-instance .
最佳答案
- 那些内置 namespace 属于 XSD 组件本身。不
schemaLocation
是必需的,因为它们的定义隐含在 XML 架构建议书。 - 符合定义的 XML 解析器将理解
xs:attribute
等 - 我不会说命名空间毫无意义。超越成为一种方式 区分以其他方式命名的组件、 namespace 也可用于将组件的使用与其相关联 另一个 XSD 中的集体定义。
- 如 #1 所述,
http://www.w3.org/2001/XMLSchema-instance
是一个 由组件组成的内置命名空间,其定义是 XML Schema Recommendation 已经暗示了这一点。
关于没有 schemaLocation 的 XMLSchema 和 XMLSchema 实例 namespace ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32135573/