1、准备知识
- XML命名空间
XML命名空间为防止xml元素命名冲突提供了解决方案。
- 命名冲突
对于一个XML文件,它的元素名称是由开发者定义的。当合并不同应用的XML文档时经常会导致命名冲突。
下面的XML代码一段HTML表格信息:
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>
下面的XML表示一张桌子的信息:
<name>African Coffee Table</name>
<width>80</width>
<length>120</length>
</table>
如果把这两段XML合并起来,就会发生命名冲突。都含有一个<table>元素,但是格子的内容和含义不同。
XML解析器不知道如何处理这些差异。
- 使用前缀解决命名冲突
使用名称前缀可以很容易的避免命名冲突。
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
上面的例子中不存在冲突,因为两个<table>元素有不同的名字。
- XML命名空间-xmlns属性
在XML中使用前缀时时,必需定义命名空间。
通过在元素的开头放置xmlns属性来定义命名空间。
定义命名空间的语法:xmlns:prefix="URI"。
<h:table xmlns:h="http://www.w3.org/TR/html4/">
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table xmlns:f="http://www.w3schools.com/furniture">
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>
上面的例子中,<table>标签中的xmlns属性赋予前缀h:和f:一个命名空间。
当一个元素定义了命名空间之后,所有具有相同前缀的子元素都和相同的命名空间关联。
命名空间可以在XML根元素处定义。
xmlns:f="http://www.w3schools.com/furniture">
<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>
Note: 解析器在查找信息的时候不会使用命名空间的URI。作用只是给命名空间一个独特的名字。
- 默认命名空间
为元素定义一个默认的命名空间,可以应用到所有的子元素上。语法如下:
下面的XML表示一个HMTL表格信息:
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>
下面的XML表示家具信息:
<name>African Coffee Table</name>
<width>80</width>
<length>120</length>
</table>
- 命名空间的实际应用
XSLT是一种XML语言,它可以把XML文档翻译成其他的格式,比如HTML。
在下面的XSLT标签中,你会发现大部分标签都是HTML标签。
不是HMTL的标签都有xsl前缀,通过命名空间xmlns:xsl="http://www.w3.org/1999/XSL/Transform"标识:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr>
<th style="text-align:left">Title</th>
<th style="text-align:left">Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
2、WSDL
WSDL是一个基于XML的语言,它用来描述Web Service以及如何访问这些Web Service。
WSDL的作用
- WSDL 全称是Web Services Description Language
- WSDL 是用XML写的
- WSDL 是一个XML文档
- WSDL 用来描述Web Service
- WSDL 也用来定位Web Servcie
- WSDL 是W3C 推荐使用
WSDL文档使用下面几个主要的元素来描述Web Service:
Element | Description |
---|---|
<types> | A container for data type deFinitions used by the web service |
<message> | A typed deFinition of the data being communicated |
<portType> | A set of operations supported by one or more endpoints |
A protocol and data format specification for a particular port type |