xml简介简单xml代码
关于本教程
我应该学习本教程吗?
这本新修订的教程讨论了XML是什么,为什么开发XML以及它如何塑造电子商务的未来。 在此过程中,它还将介绍几种XML标准和编程接口,展示如何开始使用该技术,并描述了两家公司如何构建基于XML的解决方案来简化和简化其企业。
在本教程中,您将学习:
- 为什么创建XML
- XML文档规则
- 如何定义XML文档可以包含和不能包含的内容
- 使用XML文档的编程接口
- XML的主要标准是什么以及它们如何协同工作
- 公司在现实世界中如何使用XML
什么是XML?
介绍
XML,或可扩展标记语言,是一种可用于创建自己的标记的标记语言。 它是由万维网联盟(W3C)创建的,旨在克服HTML(超文本标记语言)的限制,HTML是所有网页的基础。 像HTML一样,XML基于SGML(标准通用标记语言)。 尽管SGML在出版业中已经使用了数十年,但它的感知复杂性使许多本来可能会使用它的人感到害怕(SGML也代表“听起来不错,也许以后”)。 XML的设计考虑了Web。
我们为什么需要XML?
HTML是有史以来最成功的标记语言。 您几乎可以在任何设备上查看最简单HTML标签,从掌上电脑到大型机,甚至可以使用正确的工具将HTML标记转换为语音和其他格式。 鉴于HTML的成功,W3C为什么要创建XML? 要回答该问题,请查看以下文档:
<p><b>Mrs. Mary McGoon</b>
<br>
1401 Main Street
<br>
Anytown, NC 34829</p>
HTML的麻烦之处在于它在设计时就考虑到了人类。 即使没有在浏览器中查看上述HTML文档,您和我也可以确定这是某人的邮政地址。 (具体来说,这是美国某人的邮政地址;即使您不熟悉美国邮政地址的所有组成部分,也可能会猜出这是什么意思。)
作为人类,您和我都有能力去理解大多数文档的含义和意图。 不幸的是,机器无法做到这一点。 虽然本文档中的标签告诉浏览器如何显示此信息,但是标签不告诉浏览器该信息是什么 。 您和我知道这是一个地址,但是一台机器不是。
渲染HTML
为了呈现HTML,浏览器仅遵循HTML文档中的指令。 段落标记告诉浏览器开始在新行上进行渲染,通常预先带有空白行,而两个中断标记告诉浏览器前进到下一行而中间没有空白行。 尽管浏览器可以很好地格式化文档,但是机器仍然不知道这是一个地址。
图1. HTML地址
处理HTML
要结束对示例HTML文档的讨论,请考虑从该地址提取邮政编码的任务。 这是一种用于查找HTML标记中的邮政编码的(故意脆弱的)算法:
如果找到带有两个<br>
标记的段落,则邮政编码是第二个break标记中第一个逗号之后的第二个单词。
尽管此算法适用于本示例,但全世界有许多完全有效的地址根本无法使用。 即使您可以编写一种算法来找到用HTML编写的任何地址的邮政编码,也可以有任意数量的带有两个中断标记的段落根本不包含地址。 编写一个可以查看任何HTML段落并在其中找到任何邮政编码的算法将非常困难,即使不是不可能。
XML文档样本
现在,让我们看一个示例XML文档。 使用XML,您可以为文档中的标签分配一些含义。 更重要的是,机器也很容易处理信息。 您可以通过简单地定位由<postal-code>
和</postal-code>
标记(技术上称为<postal-code>
元素)包围的内容来从此文档中提取邮政编码。
<address>
<name>
<title>Mrs.</title>
<first-name>
Mary
</first-name>
<last-name>
McGoon
</last-name>
</name>
<street>
1401 Main Street
</street>
<city>Anytown</city>
<state>NC</state>
<postal-code>
34829
</postal-code>
</address>
标签,元素和属性
有三种用于描述XML文档各部分的通用术语: 标签 , 元素和属性 。 这是说明这些术语的样本文档:
<address>
<name>
<title>Mrs.</title>
<first-name>
Mary
</first-name>
<last-name>
McGoon
</last-name>
</name>
<street>
1401 Main Street
</street>
<city state="NC">Anytown</city>
<postal-code>
34829
</postal-code>
</address>
- 标记是左尖括号(
<
)和右尖括号(>
)之间的文本。 有开始标记(例如<name>
)和结束标记(例如</name>
) - 元素是开始标签,结束标签以及介于两者之间的所有内容。 在上面的示例中,
<name>
元素包含三个子元素:<title>
,<first-name>
和<last-name>
。 - 属性是元素的开始标记内的名称/值对。 在此示例中,
state
是<city>
元素的属性; 在以前的示例中,<state>
是一个元素(请参阅示例XML文档 )。
XML如何改变网络
既然您已经了解了开发人员如何使用XML创建具有自描述数据的文档,那么让我们看看人们如何使用这些文档来改进Web。 以下是一些关键领域:
- XML简化了数据交换。 由于不同的组织(甚至是同一组织的不同部分)很少标准化一套工具,因此应用程序进行通信需要大量工作。 每个小组都使用XML创建一个实用程序,该实用程序将其内部数据格式转换为XML,反之亦然。 最好的是,他们的软件供应商很有可能已经提供了将其数据库记录(或LDAP目录或采购订单等)与XML相互转换的工具。
- XML支持智能代码。 因为XML文档的结构可以识别每个重要的信息(以及信息之间的关系),所以可以编写无需人工干预即可处理这些XML文档的代码。 软件供应商花费大量时间和金钱来构建XML开发工具这一事实意味着编写代码是一个相对简单的过程。
- XML支持智能搜索。 尽管这些年来搜索引擎一直在稳步改进,但从搜索中获得错误的结果仍然很普遍。 如果您在HTML页面上搜索名为“ Chip”的用户,则可能还会在巧克力片,计算机片,木片以及许多其他无用的匹配项上找到页面。 在XML文档中搜索包含文本
Chip
<first-name>
元素将为您提供更好的结果。
我还将在案例研究中讨论XML的实际用法。
XML文档规则
概述:XML文档规则
如果您查看过HTML文档,则熟悉使用标签标记文档文本的基本概念。 本节讨论HTML文档和XML文档之间的区别。 它介绍了XML文档的基本规则,并讨论了用于描述它们的术语。
关于XML文档的重要一点: XML规范要求解析器拒绝任何不遵循基本规则的XML文档。 大多数HTML解析器都会接受草率的标记,从而猜测文档编写者的意图。 为了避免在普通HTML文档中发现松散的结构混乱,XML的创建者决定从一开始就强制执行文档结构。
(顺便说一句,如果您不熟悉该术语,那么解析器就是一段试图读取文档并解释其内容的代码。)
无效,有效且格式正确的文档
XML文档共有三种:
- 无效的文档不遵循XML规范定义的语法规则。 如果开发人员已经定义了文档可以在DTD或架构中包含的内容的规则,但是该文档不遵循这些规则,则该文档也将无效。 (有关对XML文档的DTD和模式的正确介绍,请参阅定义文档内容 。)
- 有效文档同时遵循XML语法规则和在其DTD或架构中定义的规则。
- 格式正确的文档遵循XML语法规则,但没有DTD或架构。
根元素
XML文档必须包含在单个元素中。 该单个元素称为root元素 ,它包含文档中的所有文本和任何其他元素。 在下面的示例中,XML文档包含在单个元素<greeting>
元素中。 请注意,文档的注释位于root元素之外; 那是完全合法的。
<?xml version="1.0"?>
<!-- A well-formed document -->
<greeting>
Hello, World!
</greeting>
这是不包含单个根元素的文档:
<?xml version="1.0"?>
<!-- An invalid document -->
<greeting>
Hello, World!
</greeting>
<greeting>
Hola, el Mundo!
</greeting>
无论文档可能包含什么信息,都需要XML解析器来拒绝该文档。
元素不能重叠
XML元素不能重叠。 这是一些不合法的标记:
<!-- NOT legal XML markup -->
<p>
<b>I <i>really
love</b> XML.
</i>
</p>
如果在<b>
<i>
元素内开始<i>
元素,则也必须在此结束。 如果希望文本XML
以斜体显示,则需要添加第二个<i>
元素以更正标记:
<!-- legal XML markup -->
<p>
<b>I <i>really
love</i></b>
<i>XML.</i>
</p>
XML解析器将仅接受此标记。 大多数Web浏览器中HTML解析器都会接受两者。
需要结束标签
您不能遗漏任何结束标签。 在下面的第一个示例中,标记不合法,因为没有结尾段落( </p>
)标签。 尽管这在HTML(在某些情况下为SGML)中可以接受,但XML解析器将拒绝它。
<!-- NOT legal XML markup -->
<p>Yada yada yada...
<p>Yada yada yada...
<p>...
如果一个元素根本不包含标记,则称为空元素 ; HTML break( <br>
)和image( <img>
)元素是两个示例。 在XML文档的空元素中,可以将开始斜杠放在开始标记中。 下面的两个break元素和两个image元素对XML解析器来说意味着相同的东西:
<!-- Two equivalent break elements -->
<br></br>
<br />
<!-- Two equivalent image elements -->
<img src="../img/c.gif"></img>
<img src="../img/c.gif" />
元素区分大小写
XML元素区分大小写。 在HTML中, <h1>
和<H1>
相同; 在XML中却不是。 如果尝试用</H1>
标记结束<h1>
元素,则会出现错误。 在下面的示例中,顶部的标题是非法的,而底部的标题是正确的。
<!-- NOT legal XML markup -->
<h1>Elements are
case sensitive</H1>
<!-- legal XML markup -->
<h1>Elements are
case sensitive</h1>
属性必须带有引号
XML文档中的属性有两个规则:
- 属性必须具有值
- 这些值必须用引号引起来
比较下面的两个示例。 顶部的标记在HTML中合法,但在XML中不合法。 要在XML中执行等效操作,必须为属性赋予一个值,并且必须将其用引号引起来。
<!-- NOT legal XML markup -->
<ol compact>
<!-- legal XML markup -->
<ol compact="yes">
只要您保持一致,就可以使用单引号或双引号。
如果属性的值包含单引号或双引号,则可以使用另一种引号将值引起来(例如在name="Doug's car"
),或使用实体"
双引号和'
单引号。 实体是一个符号,例如"
XML解析器替换为其他文本,例如"
。
XML声明
大多数XML文档都以XML声明开头,该声明向解析器提供有关文档的基本信息。 建议使用XML声明,但不是必需的。 如果有一个,则必须是文档中的第一件事。
该声明最多可以包含三个名称/值对(许多人称它们为属性,尽管从技术上讲不是这样)。 version
是所使用的XML版本。 当前,该值必须为1.0
。 encoding
是本文档中使用的字符集。 此声明中引用的ISO-8859-1
字符集包括大多数西欧语言使用的所有字符。 如果未指定encoding
,则XML解析器将假定字符位于UTF-8
集合中,这是Unicode标准,几乎支持世界语言中的每个字符和表意文字。
<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
最后, standalone,
可以是yes
或no
)定义是否可以在不读取任何其他文件的情况下处理此文档。 例如,如果XML文档未引用任何其他文件,则应指定standalone="yes"
。 如果XML文档引用了描述该文件可以包含的内容的其他文件(有关这些文件的详细信息,请稍后),您可以指定standalone="no"
。 由于standalone="no"
是默认设置,因此您很少在XML声明中看到standalone
。
XML文档中的其他内容
您可能会在XML文档中找到其他一些内容:
- 注释:注释可以出现在文档中的任何位置; 它们甚至可以出现在根元素之前或之后。 注释以
<!--
开头-->
结束。 注释的末尾不能包含双连字符(--
); 除此之外,评论可以包含任何内容。 最重要的是,注释内的任何标记都将被忽略; 如果要删除XML文档的较大部分,只需将该部分包装在注释中即可。 (要恢复已注释掉的部分,只需删除注释标记。)这是一些包含注释的标记:
<!-- Here's a PI for Cocoon: -->
<?cocoon-process type="sql"?>
- 处理指令:处理指令是针对特定代码的标记。 在上面的示例中,有一个针对Cocoon的处理指令(有时称为PI),Cocoon是来自Apache Software Foundation的XML处理框架。 当Cocoon处理XML文档时,它将查找以
cocoon-process
开头的处理指令,然后相应地处理XML文档。 在此示例中,type="sql"
属性告诉Cocoon XML文档包含一个SQL语句。
<!-- Here's an entity: -->
<!ENTITY dw "developerWorks">
- 实体:上面的示例为文档定义了一个实体 。 XML处理器找到字符串
&dw;
任何地方&dw;
,它将实体替换为字符串developerWorks
。 XML规范还定义了五个实体,您可以使用它们代替各种特殊字符。 实体是:-
<
小于号 -
>
大于号 -
"
双引号 -
'
单引号(或撇号) -
&
一个“&”号。
-
命名空间
XML的强大功能来自其灵活性,事实是您和我以及数百万其他人可以定义我们自己的标记来描述我们的数据。 还记得样本XML文档中有关一个人的姓名和地址的信息吗? 该文档包括一个人的礼貌标题的<title>
元素,这是元素名称的完美选择。 如果您经营在线书店,则可以为书名创建<title>
元素。 如果您经营一家在线抵押公司,则可以为一个财产的标题创建一个<title>
元素。 所有这些都是合理的选择,但是所有这些创建的名称都相同。 如何确定给定的<title>
元素是指某个人,一本书还是一件财产? 具有名称空间 。
要使用名称空间,您可以定义名称空间前缀并将其映射到特定的字符串。 这是为三个<title>
元素定义名称空间前缀的方法:
<?xml version="1.0"?>
<customer_summary
xmlns:addr="http://www.xyz.com/addresses/"
xmlns:books="http://www.zyx.com/books/"
xmlns:mortgage="http://www.yyz.com/title/"
>
... <addr:name><title>Mrs.</title> ... </addr:name> ...
... <books:title>Lord of the Rings</books:title> ...
... <mortgage:title>NC2948-388-1983</mortgage:title> ...
在此示例中,三个名称空间前缀为addr
, books
和mortgage
。 请注意,为特定元素定义名称空间意味着其所有子元素都属于同一名称空间。 第一个<title>
元素属于addr
命名空间,因为它的父元素<addr:Name>
确实存在。
最后一点: 名称空间定义中的字符串只是一个字符串。 是的,这些字符串看起来像URL,但不是。 您可以定义xmlns:addr="mike"
,它也可以正常工作。 关于名称空间字符串唯一重要的是它的唯一性。 这就是为什么大多数名称空间定义看起来像URL的原因。 XML解析器不会转到http://www.zyx.com/books/
来搜索DTD或模式,它只是将该文本用作字符串。 令人困惑,但这就是名称空间的工作方式。
定义文件内容
概述:定义文档内容
到目前为止,您已经在本教程中了解了XML文档的基本规则。 一切都很好,但是您需要定义将用于表示数据的元素。 在本节中,您将学习两种实现方法。
- 一种方法是使用文档类型定义或DTD。 DTD定义了可以在XML文档中出现的元素,它们出现的顺序,如何相互嵌套以及XML文档结构的其他基本细节。 DTD是原始XML规范的一部分,与SGML DTD非常相似。
- 另一种方法是使用XML模式。 模式可以定义可放入DTD的所有文档结构,并且还可以定义数据类型和比DTD更复杂的规则。 W3C在原始XML规范之后的几年开发了XML Schema规范。
文件类型定义
DTD允许您指定XML文档的基本结构。 接下来的几节介绍DTD的片段。 首先,这是一个DTD,它定义了什么是XML一节中的地址文档示例的基本结构。 :
<!-- address.dtd -->
<!ELEMENT address (name, street, city, state, postal-code)>
<!ELEMENT name (title? first-name, last-name)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT first-name (#PCDATA)>
<!ELEMENT last-name (#PCDATA)>
<!ELEMENT street (#PCDATA)>
<!ELEMENT city (#PCDATA)>
<!ELEMENT state (#PCDATA)>
<!ELEMENT postal-code (#PCDATA)>
该DTD定义了样本文档中使用的所有元素。 它定义了三个基本内容:
-
<address>
元素包含<name>
,<street>
,<city>
,<state>
和<postal-code>
。 所有这些元素都必须出现,并且必须按该顺序出现。 -
<name>
元素包含一个可选的<title>
元素(问号表示标题是可选的),后跟一个<first-name>
和<last-name>
元素。 - 所有其他元素都包含文本。 (
#PCDATA
代表已解析的字符数据;您不能在这些元素中包含另一个元素。)
尽管DTD非常简单,但它可以清楚说明哪些元素组合是合法的。 在<state>
<postal-code>
元素之前具有<postal-code>
元素的地址文档是不合法的,并且没有<last-name>
元素的地址文档也不合法。
另外,请注意,DTD语法与普通XML语法不同。 (相比之下,XML Schema文档本身就是XML,这会带来一些有趣的后果。)尽管DTD的语法不同,但是您仍然可以在DTD本身中添加普通注释。
DTD中的符号
在DTD中使用了一些符号来表示某些内容在XML文档中出现的频率(或是否)。 以下是一些示例及其含义:
-
<!ELEMENT address (name, city, state)>
<address>
元素必须按此顺序包含<name>
,<city>
和<state>
元素。 所有元素都是必需的。 逗号表示项目列表。 -
<!ELEMENT name (title?, first-name, last-name)>
这意味着
<name>
元素包含一个可选的<title>
元素,后跟一个强制性的<first-name>
和<last-name>
元素。 问号表示项目是可选的; 它可以出现一次或根本不出现。 -
<!ELEMENT addressbook (address+)>
一个
<addressbook>
元素包含一个或多个<address>
元素。 您可以根据需要具有任意数量的<address>
元素,但必须至少有一个。 加号表示一个项目必须至少出现一次,但可以出现任意次。 -
<!ELEMENT private-addresses (address*)>
<private-addresses>
元素包含零个或多个<address>
元素。 星号表示一个项目可以出现任意次,包括零次。 -
<!ELEMENT name (title?, first-name, (middle-initial | middle-name)?, last-name)>
<name>
元素包含一个可选的<title>
元素,后跟一个<first-name>
元素,然后可能是一个<middle-initial>
或<middle-name>
元素,然后是一个<last-name>
元件。 换句话说,<middle-initial>
和<middle-name>
都是可选的,并且您只能使用两者之一。 竖线表示选择列表; 您只能从列表中选择一项。 还要注意,该示例使用括号对某些元素进行分组,并对分组使用问号。 -
<!ELEMENT name ((title?, first-name, last-name) | (surname, mothers-name, given-name))>
<name>
元素可以包含以下两个序列之一:可选的<title>
,后跟<first-name>
和<last-name>
; 或<surname>
,<mothers-name>
和<given-name>
。
关于灵活性的一句话
在继续之前,简要介绍一下设计XML文档类型以提高灵活性。 考虑样本名称和地址文档类型; 我清楚地写出了它,并牢记美国的邮政地址。 如果要为其他类型的地址定义规则的DTD或架构,则必须为其增加更多的复杂性。 在澳大利亚,要求使用<state>
元素可能很有意义,但在英国则不需要。 可以通过文档类型定义中的示例DTD处理加拿大地址,但是添加<province>
元素是一个更好的主意。 最后,请注意,在世界许多地方,标题,名字和姓氏等概念都没有意义。
最重要的是:如果要定义XML文档的结构,则应该像在应用程序中设计数据库模式或数据结构时那样,在DTD或模式中投入更多的精力。 您可以预见的将来需求越多,以后实现它们就越容易和便宜。
定义属性
本入门教程并未详细介绍DTD的工作原理,但这里要介绍的另一个基本主题是:定义属性。 您可以为将出现在XML文档中的元素定义属性。 使用DTD,您还可以:
- 定义哪些属性是必需的
- 定义属性的默认值
- 列出给定属性的所有有效值
假设您想更改DTD以使state
为<city>
元素的属性。 这样做的方法如下:
<!ELEMENT city (#PCDATA)>
<!ATTLIST city state CDATA #REQUIRED>
它像以前一样定义了<city>
元素,但是修改后的示例还使用了ATTLIST
声明来列出该元素的属性。 属性列表中的名称city
告诉解析器这些属性是为<city>
元素定义的。 名称state
是属性的名称,关键字CDATA
和#REQUIRED
告诉解析器state
属性包含文本并且是必需的(如果是可选的,则CDATA #IMPLIED
可以解决问题)。
要为一个元素定义多个属性,请像这样编写ATTLIST
:
<!ELEMENT city (#PCDATA)>
<!ATTLIST city state CDATA #REQUIRED
postal-code CDATA #REQUIRED>
此示例将state
和postal-code
都定义为<city>
元素的属性。
最后,DTD允许您定义属性的默认值并枚举属性的所有有效值:
<!ELEMENT city (#PCDATA)>
<!ATTLIST city state CDATA (AZ|CA|NV|OR|UT|WA) "CA">
此处的示例表明,它仅支持来自亚利桑那州(AZ),加利福尼亚州(CA),内华达州(NV),俄勒冈州(OR),犹他州(UT)和华盛顿州(WA)的地址,默认状态为加利福尼亚 因此,您可以执行非常有限的数据验证形式。 尽管这是一个有用的功能,但是它只是您可以使用XML模式做的一小部分(请参阅XML模式 )。
XML模式
使用XML模式,您可以更有能力定义有效的XML文档的外观。 与DTD相比,它们具有以下优点:
- XML模式使用XML语法。 换句话说,XML模式是XML文档。 这意味着您可以像处理其他任何文档一样处理架构。 例如,您可以编写一个XSLT样式表,该表将XML模式转换为Web表单,并带有自动生成JavaScript代码,该代码在输入数据时对数据进行验证。
- XML模式支持数据类型。 尽管DTD确实支持数据类型,但很显然,这些数据类型是从发布角度开发的。 XML模式支持DTD的所有原始数据类型(诸如ID和ID引用之类的东西)。 它们还支持整数,浮点数,日期,时间,字符串,URL和其他对数据处理和验证有用的数据类型。
- XML模式是可扩展的。 除了XML模式规范中定义的数据类型外,您还可以创建自己的数据类型,并可以基于其他数据类型派生新的数据类型。
- XML模式具有更强大的表达能力。 例如,使用XML模式,您可以定义任何
<state>
属性的值不能超过2个字符,或者任何<postal-code>
元素的值都必须与正则表达式[0-9]{5}(-[0-9]{4})?
。 使用DTD不能做任何一件事情。
XML模式样本
这是一个与原始名称和地址DTD相匹配的XML模式。 它增加了两个约束: <state>
元素的值必须恰好是两个字符长,并且<postal-code>
元素的值必须与正则表达式[0-9]{5}(-[0-9]{4})?
。 尽管该模式比DTD长得多,但它可以更清楚地表示有效文档的外观。 这是模式:
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="address">
<xsd:complexType>
<xsd:sequence>
<xsd:element ref="name"/>
<xsd:element ref="street"/>
<xsd:element ref="city"/>
<xsd:element ref="state"/>
<xsd:element ref="postal-code"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="name">
<xsd:complexType>
<xsd:sequence>
<xsd:element ref="title" minOccurs="0"/>
<xsd:element ref="first-Name"/>
<xsd:element ref="last-Name"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="title" type="xsd:string"/>
<xsd:element name="first-Name" type="xsd:string"/>
<xsd:element name="last-Name" type="xsd:string"/>
<xsd:element name="street" type="xsd:string"/>
<xsd:element name="city" type="xsd:string"/>
<xsd:element name="state">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:length value="2"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="postal-code">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:pattern value="[0-9]{5}(-[0-9]{4})?"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
</xsd:schema>
在架构中定义元素
示例 XML模式中的XML模式使用<xsd:element>
元素定义了许多XML元素。 定义的前两个元素<address>
和<name>
由其他元素组成。 <xsd:sequence>
元素定义每个元素中包含的元素的顺序。 这是一个例子:
<xsd:element name="address">
<xsd:complexType>
<xsd:sequence>
<xsd:element ref="name"/>
<xsd:element ref="street"/>
<xsd:element ref="city"/>
<xsd:element ref="state"/>
<xsd:element ref="postal-code"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
与DTD版本一样,XML模式示例定义<address>
依次包含<name>
, <street>
, <city>
, <state>
和<postal-code>
元素。 请注意,该架构实际上使用<xsd:complexType>
元素定义了新的数据类型。
大多数元素包含文本; 定义它们很简单。 您只需声明新元素,然后将其数据类型指定为xsd:string
:
<xsd:element name="title" type="xsd:string"/>
<xsd:element name="first-Name" type="xsd:string"/>
<xsd:element name="last-Name" type="xsd:string"/>
<xsd:element name="street" type="xsd:string"/>
<xsd:element name="city" type="xsd:string"/>
在架构中定义元素内容
该示例架构为两个元素的内容定义了约束: <state>
元素的内容必须为两个字符长,并且<postal-code>
元素的内容必须与正则表达式[0-9]{5}(-[0-9]{4})?
相匹配。 [0-9]{5}(-[0-9]{4})?
。 这样做的方法如下:
<xsd:element name="state">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:length value="2"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="postal-code">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:pattern value="[0-9]{5}(-[0-9]{4})?"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
对于<state>
和<postal-code>
元素,该架构定义了具有限制的新数据类型。 第一种情况使用<xsd:length>
元素,第二种情况使用<xsd:pattern>
元素定义该元素必须匹配的正则表达式。
本摘要仅概述XML模式可以做什么。 有整本关于这个主题的书。 出于介绍的目的,足以说XML模式是描述有效XML文档外观的非常强大且灵活的方式。
XML编程接口
概述:XML编程接口
本节介绍XML的各种编程接口。 这些接口为开发人员提供了用于处理XML文档的一致接口。 有许多可用的API。 本节介绍了四个最受欢迎且最有用的工具:文档对象模型(DOM),XML的简单API(SAX),JDOM和XML解析的Java API(JAXP)。
文档对象模型
通常称为DOM的文档对象模型定义了一组与XML文档的已解析版本的接口。 解析器读取整个文档并构建一个内存中的树,因此您的代码可以使用DOM接口来操纵该树。 您可以在树中移动以查看原始文档中包含的内容,可以删除树的各个部分,可以重新排列树,添加新的分支,等等。
DOM由W3C创建,是该联盟的官方建议。
DOM问题
DOM提供了丰富的功能集,可用于解释和操作XML文档,但是这些功能是有代价的。 在开发XML文档的原始DOM时,XML-DEV邮件列表上的许多人对此表示了担忧:
- DOM构建整个文档的内存树。 如果文档很大,则需要大量内存。
- DOM创建的对象代表原始文档中的所有内容,包括元素,文本,属性和空白。 如果您只关心原始文档的一小部分,那么创建所有永远不会使用的对象将非常浪费。
- 在您的代码得到控制之前,DOM解析器必须读取整个文档。 对于非常大的文档,这可能会导致严重的延迟。
这些仅仅是文档对象模型的设计所引起的问题。 尽管存在这些问题, 但DOM API是解析XML文档的一种非常有用的方法。
XML的简单API
为了解决DOM问题,XML-DEV参与者(由David Megginson领导)创建了SAX接口。 SAX具有解决DOM问题的几个特征:
- SAX解析器将事件发送到您的代码。 解析器告诉您何时找到元素的开头,元素的结尾,文本,文档的开头或结尾,等等。 您决定哪些事件对您很重要,并决定要创建哪种数据结构来保存这些事件中的数据。 如果您未明确保存事件中的数据,则将其丢弃。
- SAX解析器根本不创建任何对象,而只是将事件传递给您的应用程序。 如果要基于这些事件创建对象,则由您决定。
- 解析开始后,SAX解析器即开始向您传递事件。 当解析器找到文档的开头,找到元素的开头,找到文本等时,您的代码将获得一个事件。 您的应用程序立即开始生成结果。 您不必等待整个文档都已解析。 更好的是,如果您仅在文档中查找某些内容,则一旦找到所需的内容,您的代码就会引发异常。 该异常会停止SAX解析器,并且您的代码可以对发现的数据进行任何处理。
说完所有这些,SAX和DOM都有自己的位置。 本节的其余部分讨论为什么您可能要使用一个界面或另一个界面。
SAX问题
公平地说,SAX解析器还存在一些可能引起关注的问题:
- SAX事件是无状态的。 当SAX解析器在XML文档中找到文本时,它将事件发送给您的代码。 该事件只是向您提供找到的文本。 它不会告诉您什么元素包含该文本。 如果您想知道这一点,则必须自己编写状态管理代码。
- SAX事件不是永久性的。 如果您的应用程序需要用于对XML文档建模的数据结构,则必须自己编写该代码。 如果需要访问SAX事件中的数据,并且没有将数据存储在代码中,则必须再次解析文档。
- SAX不受中央管理的组织的控制。 尽管到目前为止这还没有引起问题 ,但是如果SAX由W3C之类的组织控制,则某些开发人员会感到更加自在。
JDOM
由于对使用DOM和SAX模型执行某些任务的困难感到沮丧,Jason Hunter和Brett McLaughlin创建了JDOM包。 JDOM是一个基于Java技术的开源项目,它试图遵循80/20规则:使用DOM和SAX中20%的功能交付80%的用户需要的东西。 JDOM与SAX和DOM解析器一起使用,因此它以相对较小的Java类集的形式实现。
JDOM的主要特征是它大大减少了您必须编写的代码量。 尽管本入门教程没有深入讨论编程主题,但JDOM应用程序的时间通常是DOM应用程序的三分之一,而SAX应用程序的长度大约是其一半。 (当然,DOM纯粹主义者建议,学习和使用DOM是一门很好的学科,从长远来看会有所收获。)JDOM并不能做所有事情,但是对于您要进行的大多数解析,这可能只是事情。
用于XML解析的Java API
尽管DOM,SAX和JDOM为大多数常见任务提供了标准接口,但仍有一些它们无法解决的问题。 例如,在Java程序中创建DOMParser
对象的过程与一个DOM分析器不同。 为了解决此问题,Sun已发布了JAXP(用于XML解析的Java API)。 该API提供了用于使用DOM,SAX和XSLT处理XML文档的通用接口。
JAXP提供了诸如DocumentBuilderFactory
和DocumentBuilder
接口,它们为不同的解析器提供了标准接口。 还有一些方法可以让您控制基础解析器是否支持名称空间,以及它是否使用DTD或架构来验证XML文档。
哪个界面适合您?
To determine which programming interface is right for you, you need to understand the design points of all of the interfaces, and you need to understand what your application needs to do with the XML documents you're going to process. Consider these questions to help you find the right approach.
- Will your application be written in Java? JAXP works with DOM, SAX, and JDOM; if you're writing your code in Java, you should use JAXP to isolate your code from the implementation details of various parsers.
- How will your application be deployed? If your application is going to be deployed as a Java applet, and you want to minimize the amount of downloaded code, keep in mind that SAX parsers are smaller than DOM parsers. Also be aware that using JDOM requires a small amount of code in addition to the SAX or DOM parser.
- Once you parse the XML document, will you need to access that data many times? If you need to go back to the parsed version of the XML file, DOM is probably the right choice. When a SAX event is fired, it's up to you (the developer) to save it somehow if you need it later. If you need to access an event you didn't save, you have to parse the file again. DOM saves all of the data automatically.
- Do you need just a few things from the XML source? If you only need a few things out of the XML source, SAX is probably the right choice. SAX doesn't create objects for everything in the source document; you can decide what's important. With SAX, you can look at each event to see if it's relevant to your needs, then process it appropriately. Even better, once you've found what you're looking for, your code can throw an exception to stop the SAX parser altogether.
- Are you working on a machine with very little memory? If so, SAX is your best choice, despite all the other factors that you might consider.
Be aware that XML APIs exist for other languages; the Perl and Python communities in particular have very good XML tools.
XML standards
Overview: XML standards
A variety of standards exist in the XML universe. In addition to the base XML standard, other standards define schemas, style sheets, links, Web services, security, and other important items. This section covers the most popular standards for XML, and points you to references to find other standards.
The XML specification
This spec, located at w3.org/TR/REC-xml , defines the basic rules for XML documents. All of the XML document rules discussed earlier in this tutorial are defined here.
In addition to the basic XML standard, the Namespaces spec is another important part of XML. You can find the namespaces standard at the W3C as well: w3.org/TR/REC-xml-names/ .
XML模式
The XML Schema language is defined in three parts:
- A primer , located at w3.org/TR/xmlschema-0 , that gives an introduction to XML schema documents and what they're designed to do;
- A standard for document structures , located at w3.org/TR/xmlschema-1 , that illustrates how to define the structure of XML documents;
- A standard for data types , located at w3.org/TR/xmlschema-2 , that defines some common data types and rules for creating new ones.
This tutorial discussed schemas briefly in Defining document content ; if you want the complete details on all the things you can do with XML schemas, the primer is the best place to start.
XSL, XSLT, and XPath
The Extensible Stylesheet Language, XSL, defines a set of elements (called formatting objects) that describe how data should be formatted. For clarity, this standard is often referred to as XSL-FO to distinguish it from XSLT. Although it's primarily designed for generating high-quality printable documents, you can also use formatting objects to generate audio files from XML. The XSL-FO standard is at w3.org/TR/xsl/ .
The Extensible Stylesheet Language for Transformations, XSLT, is an XML vocabulary that describes how to convert an XML document into something else. The standard is at w3.org/TR/xslt (no closing slash).
XPath, the XML Path Language, is a syntax that describes locations in XML documents. You use XPath in XSLT style sheets to describe which portion of an XML document you want to transform. XPath is used in other XML standards as well, which is why it is a separate standard from XSLT. XPath is defined at w3.org/TR/xpath (no closing slash).
DOM
The Document Object Model defines how an XML document is converted to an in-memory tree structure. The DOM is defined in a number of specifications at the W3C:
- The Core DOM defines the DOM itself, the tree structure, and the kinds of nodes and exceptions your code will find as it moves through the tree. The complete spec is at w3.org/TR/DOM-Level-2-Core/ .
- Events defines the events that can happen to the tree, and how those events are processed. This specification is an attempt to reconcile the differences in the object models supported by Netscape and Internet Explorer since Version 4 of those browsers. This spec is at w3.org/TR/DOM-Level-2-Events/ .
- Style defines how XSLT style sheets and CSS style sheets can be accessed by a program. This spec is at w3.org/TR/DOM-Level-2-Style/ .
- Traversals and Ranges define interfaces that allow programs to traverse the tree or define a range of nodes in the tree. You can find the complete spec at w3.org/TR/DOM-Level-2-Traversal-Range/ .
- Views defines an
AbstractView
interface for the document itself. See w3.org/TR/DOM-Level-2-Views/ for more information.
SAX, JDOM, and JAXP
The Simple API for XML defines the events and interfaces used to interact with a SAX-compliant XML parser. You can find the complete SAX specification at www.saxproject.org .
The JDOM project was created by Jason Hunter and Brett McLaughlin and lives at jdom.org/ . At the JDOM site, you can find code, sample programs, and other tools to help you get started. (For developerWorks articles on JDOM, see Related topics .
One significant point about SAX and JDOM is that both of them came from the XML developer community, not a standards body. Their wide acceptance is a tribute to the active participation of XML developers worldwide.
Linking and referencing
There are two standards for linking and referencing in the XML world: XLink and XPointer:
- XLink, the XML Linking Language, defines a variety of ways to link different resources together. You can do normal point-to-point links (as with the HTML
<a>
element) or extended links, which can include multipoint links, links through third parties, and rules that define what it means to follow a given link. The XLink standard is at w3.org/TR/xlink/ . - XPointer, the XML Pointer Language, uses XPath as a way to reference other resources. It also includes some extensions to XPath. You can find the spec at www.w3.org/TR/xptr/ .
安全
There are two significant standards that address the security of XML documents. One is the XML Digital Signature standard ( w3.org/TR/xmldsig-core/ ), which defines an XML document structure for digital signatures. You can create an XML digital signature for any kind of data, whether it's an XML document, an HTML file, plain text, binary data, and so on. You can use the digital signature to verify that a particular file wasn't modified after it was signed. If the data you're signing is an XML document, you can embed the XML document in the signature file itself, which makes processing the data and the signature very simple.
The other standard addresses encrypting XML documents. While it's great that XML documents can be written so that a human can read and understand them, this could mean trouble if a document fell into the wrong hands. The XML Encryption standard ( w3.org/TR/xmlenc-core/ ) defines how parts of an XML document can be encrypted.
Using these standards together, you can use XML documents with confidence. I can digitally sign an important XML document, generating a signature that includes the XML document itself. I can then encrypt the document (using my private key and your public key) and send it to you. When you receive it, you can decrypt the document with your private key and my public key; that lets you know that I'm the one who sent the document. (If need be, you can also prove that I sent the document.) Once you've decrypted the document, you can use the digital signature to make sure the document has not been modified in any way.
网页服务
Web services are an important new kind of application. A Web service is a piece of code that can be discovered, described, and accessed using XML. There is a great deal of activity in this space, but the three main XML standards for Web services are:
- SOAP: Originally the Simple Object Access Protocol, SOAP defines an XML document format that describes how to invoke a method of a remote piece of code. My application creates an XML document that describes the method I want to invoke, passing it any necessary parameters, and then it sends that XML document across a network to that piece of code. The code receives the XML document, interprets it, invokes the method I requested, then sends back an XML document that describes the results. Version 1.1 of the SOAP spec is at w3.org/TR/SOAP/ . Visit w3.org/TR/ to see all of the W3C's SOAP-related activities.
- WSDL: The Web Services Description Language is an XML vocabulary that describes a Web service. It's possible to write a piece of code that takes a WSDL document and invokes a Web service it's never seen before. The information in the WSDL file defines the name of the Web service, the names of its methods, the arguments to those methods, and other details. You can find the latest WSDL spec at w3.org/TR/wsdl (no closing slash).
- UDDI: The Universal Description, Discovery, and Integration protocol defines a SOAP interface to a registry of Web services. If you have a piece of code that you'd like to deploy as a Web service, the UDDI spec defines how to add the description of your service to the registry. If you're looking for a piece of code that provides a certain function, the UDDI spec defines how to query the registry to find what you want. The source of all things UDDI is uddi.org .
Other standards
A number of other XML standards exist that I don't go into here. In addition to widely-applicable standards like Scalable Vector Graphics ( www.w3.org/TR/SVG/ ) and SMIL, the Synchronized Multimedia Integration Language ( www.w3.org/TR/smil20/ ), there are many industry-specific standards. For example, the HR-XML Consortium has defined a number of XML standards for Human Resources; you can find those standards at hr-xml.org .
Finally, for a good source of XML standards, visit Cover Pages for information on many XML schemas and other resources . This site features standards for a wide variety of industries.
Case studies
Real-world examples
By this point, I hope you're convinced that XML has tremendous potential to revolutionize the way eBusiness works. While potential is great, what really counts are actual results in the marketplace. This section describes three case studies in which organizations have used XML to streamline their business processes and improve their results.
All of the case studies discussed here come from IBM's jStart program. The jStart team exists to help customers use new technologies to solve problems. When a customer agrees to a jStart engagement, the customer receives IBM consulting and development services at a discount, with the understanding that the resulting project will be used as a case study. If you'd like to see more case studies, including case studies involving web services and other new technologies, visit the jStart web page.
Be aware that the jStart team is no longer doing engagements for XML projects; the team's current focus is Web services engagements. Web services use XML in a specialized way, typically through the SOAP, WSDL, and UDDI standards mentioned earlier in Web services .
Province of Manitoba
Figure 2. Province of Manitoba

The government of the Province of Manitoba created the Personal Property Registry to provide property owners with state-of-the-art Internet services around the clock. The main benefits of the application were faster and more convenient access to property data, fewer manual steps in the property management process, and fewer calls to the government's call center. In other words, giving customers better service while saving the government money and reducing the government's workload.
应用设计
The application was designed as an n -tiered application, with the interface separated from the back-end logic. The data for each transaction needed to be transformed a number of different ways, depending on how it needed to be rendered on a device, presented to an application, or formatted for the back-end processing system. In other words, the application was a perfect opportunity to use XML.
As with any application, the user interface to the application was extremely important. To simplify the first implementation, the necessary XML data was transformed into HTML. This gave users a browser interface to the application. The registry was built with VisualAge for Java, specifically the Visual Servlet Builder component. It also uses Enterprise Java Beans (EJBs), including Session beans and Entity beans.
Generating multiple user interfaces with XML
In addition to the HTML interface, a Java client interface and a B2B electronic interface were planned as well. For all of these interfaces, the structured XML data is transformed into the appropriate structures and documents. The initial rollout of the service allowed one business partner, Canadian Securities Registration Systems, to submit XML transaction data using the Secure Sockets Layer. The XML transaction data was transformed into the appropriate format for the back-end transactions.
The end result is that the Province of Manitoba was able to create a flexible new application and their end users could access the property registry more easily and quickly. Because the province uses XML as the data format, the government IT team has a great deal of flexibility in designing new interfaces and access methods. Best of all, the back-end systems didn't have to change at all.
First Union banks on XML
Figure 3. First Union banks on XML

First Union National Bank, one of the largest banks in the US, is in the process of reengineering many of its applications using Java and XML. Like most large companies, its environment is heterogeneous, with OS/390, AIX, Solaris, HP/9000, and Windows NT servers and Windows NT, Windows 98, Solaris, and AIX clients. Given this environment, First Union chose Java for platform-independent code and XML for platform-independent data.
A messaging-based system
The bank's distributed applications are built on a messaging infrastructure, using IBM's MQSeries to deliver messages to the OS/390 system. The message content is based on a specification called the Common Interface Message (CIM), a First Union proprietary standard. Both the front-end and back-end components of the application are dependent on the message format. Using XML as the data format isolates both sides of the application from future changes and additions to the messaging protocol.
Using XML tools to automate data flows
In developing this XML-based application, the First Union and IBM team created a service that converts the CIM into an XML document. Another part of the application converts the XML request into the appropriate format for the back-end processing systems. Finally, a third service converts COBOL copy books into DTDs. Once the copy book has been converted into a DTD, First Union can use the DTD and the XML4J parser to validate the XML document automatically; the bank can then be sure that the XML document matches the COBOL data structure that OS/390 expects.
Using Java technology and XML has been very successful for First Union. According to Bill Barnett, Manager of the Distributed Object Integration Team at First Union, "The combination of Java and XML really delivered for us. Without a platform-independent environment like Java and the message protocol independence we received from the use of XML, we would not have the confidence that our distributed infrastructure could evolve to meet the demand from our ever-growing customer base."
Hewitt Associates LLC
Figure 4. Hewitt Associates LLC

Hewitt Associates LLC is a global management consulting firm that specifies in human resource solutions. The company has more than 200 corporate clients worldwide; those companies in turn have more than 10 million employees. Hewitt's clients demand timely, accurate delivery of human resources information for those 10 million employees.
Prior to its jStart engagement, Hewitt built custom, proprietary solutions when its clients requested human resources data. Those custom solutions were typically gateways to Hewitt's existing legacy applications; in some cases, the solutions dealt with the actual byte streams. These custom applications were very costly to develop, test, and deploy, leading Hewitt to investigate Web services.
Web services to the rescue!
To solve these problems, Hewitt and the jStart team worked together to build Web services to address the needs of Hewitt's customers. Web services are a new kind of application that uses XML in a number of interesting ways:
- First of all, Web services typically use SOAP, an XML standard for moving XML data from one place to another.
- Secondly, the interfaces provided by a Web service (method names, parameters, data types, etc.) are described with XML.
- Next, a Web service's description can be stored in or retrieved from a UDDI registry; all of the information that goes into or comes out of the registry is formatted as XML.
- Finally, the data that is provided by the Web service is itself XML.
Hewitt has delivered two applications that illustrate their ability to deliver data in more flexible ways:
- With the Secure Participant Mailbox, authorized users can request reports containing personalized information on retirement and other employee benefits.
- With the Retirement Access B2B Connection, authorized users can get details of a client's 401(k) financial information.
Both of these applications retrieve data from existing legacy systems, use XML to format the data, and deliver the formatted information across the Web. Because these applications are built on open standards, Hewitt can deliver them quickly. Best of all, the flexibility of these applications helps Hewitt distinguish itself from its competitors.
"We see Web services as the vehicle to provide open, non-proprietary access to our participant business services and data through a ubiquitous data network," said Tim Hilgenberg, Chief Technology Strategist at Hewitt. The end result: Hewitt develops more flexible applications faster and cheaper, clients get better access to their data, and Hewitt's existing legacy applications don't have to change.
Case studies summary
In all of these case studies, companies used XML to create a system-independent data format. The XML documents represent structured data that can be moved from one system or process to another. As front-end and back-end applications change, the XML traveling between them remains constant. Even better, as more front-end and back-end applications are added to the mix, the use of XML insulates the existing applications from any changes. As Web services become more common, XML will also be used to transport the data.
Advice
我们走吧!
At this point, I hope you're convinced that XML is the best way to move and manipulate structured data. If you're not using XML already, how do you get started? 这里有一些建议:
- Decide what data you want to convert to XML. Typically this is data that needs to be moved from one system to another, or data that has to be transformed into a variety of formats.
- See if there are any existing XML standards. If you're looking at very common data, such as purchase orders, medical records, or stock quotes, chances are good that someone out there has already defined XML standards for that data.
- See if your existing tools support XML. If you're using a recent version of a database package, a spreadsheet, or some other data management tool, it's likely that your existing tools (or upgrades to them) can use XML as an input or output format.
- Learn how to build XML-based applications. You need to understand how your data is stored now, how it needs to be transformed, and how to integrate your XML development efforts with your existing applications. Benoît Marchal's Working XML column is a great place to start; you can find a current listing of all his columns at http://www.ibm.com/developerworks/views/xml/libraryview.jsp?search_by=working+xml: .
- Join the appropriate standards groups. Consider joining groups like the World-Wide Web Consortium (W3C), as well as industry-specific groups like HR-XML.org. Being a member of these groups will help you keep track of what's happening in the industry, and it gives you the chance to shape the future of XML standards.
- Avoid proprietary shenanigans. It's important that you use only standards-based technology in your development efforts; resist the lures of vendors who offer so-called improvements to you. One of XML's advantages is that you have complete control of your data. Once it's held hostage by a proprietary data format, you've given up a tremendous amount of control.
- Contact the jStart team. If you think your enterprise could work with the jStart engagement model, contact the team to see what your possibilities are.
- Stay tuned to developerWorks . Our XML zone has thousands of pages of content that deal with various XML topics, including DTD and schema development, XML programming, and creating XSLT style sheets.
翻译自: https://www.ibm.com/developerworks/xml/tutorials/xmlintro/xmlintro.html
xml简介简单xml代码