可扩展标记语言(XML)常令人望而生畏。虽耳熟能详,但多数人并不清楚其本质。XML 促进了网站与应用程序间的数据交换,是电子商务、Google 站点地图、RSS 订阅源及播客等技术背后的核心驱动力。
作为一种“标记语言”,XML 通过标签系统识别离散信息单元以便处理。相较于 HTML,XML 专为网络文档设计,仅聚焦数据本身,允许自定义标签和属性,适用范围涵盖电商交易、数学公式至矢量图形等。简言之,XML 描述的是数据。
XML 是一种用于在网络上标识和显示信息的标记语言(标签系统)。
借助样式表,XML 可在 Web 浏览器中格式化显示。相比 HTML,搜索引擎及自动化应用能从 XML 中提取更多语义。作为 HTML 的未来演进方向,XML 值得深入了解。
本教程将介绍 XML 结构并创建简单文档;下期将讲解如何使用层叠样式表(CSS)格式化 XML 以供浏览器查看,并演示如何创建 Google 站点地图及 RSS 订阅源。
XML 文档构建
首先审视需结构化的数据。以在售产品为例,需记录名称、价格、描述和重量。XML 允许创建自定义标签容纳信息,不受限于 HTML 预定义标签集。
示例数据结构如下:
- Product #1
Price: $29.99 | Weight: 5 lbs.
Description: This is product one, and it is a beauty. - Product #2
Price: $35.99 | Weight: 5.6 ounces
Description: Product two is smaller and weighs less, but is more expensive.
上述信息已按产品分组。接下来基于此创建首个 XML 文档。
所有 XML 文档均以文档类型声明开头。首行代码创建名为 products.xml 的文本文件:
<?xml version="1.0" encoding="iso-8859-1"?>
该行定义了 XML 版本与字符编码。随后插入产品数据,先创建根标签描述产品集合:
<?xml version="1.0" encoding="iso-8859-1"?> <products> </products>
起始与结束标签之间留空,所有产品信息置于其中。接着为第一个产品创建 <item> 标签:
<?xml version="1.0" encoding="iso-8859-1"?> <products> <item> </item> </products>
在 <item> 标签内预留空间存放具体信息。针对标题、价格、重量和描述四个字段,创建对应子标签并填入内容:
<?xml version="1.0" encoding="iso-8859-1"?>
<products>
<item>
<title>Product #1</title>
<price>29.99</price>
<weight>5</weight>
<description>This is product one, and it is a beauty.</description>
</item>
</products>
标签命名与数据强相关,便于理解。由于文档结构维持了元素间关系,标签名称可自定义。<item></item> 内的所有内容均属于单个产品。添加第二个产品时,只需在首个 <item> 后新增一组标签:
<?xml version="1.0" encoding="iso-8859-1"?>
<products>
<item>
<title>Product #1</title>
<price>29.99</price>
<weight>5</weight>
<description>This is product one, and it is a beauty.</description>
</item>
<item>
<title>Product #2</title>
<price>35.99</price>
<weight>5.6</weight>
<description>Product two is smaller and weighs less, but is more expensive.</description>
</item>
</products>
至此,一个简单的产品列表 XML 文档已完成。它以层次结构组织,包含产品信息及其关联关系。
当前文档缺少计量单位信息。XML 标签支持类似 HTML 的属性,适用于描述数据元信息(如度量单位),而非直接承载数值。因此,为重量标签添加 units 属性,并为价格标签添加 currency 属性以补充原始列表中隐含的货币信息:
<?xml version="1.0" encoding="iso-8859-1"?>
<products>
<item>
<title>Product #1</title>
<price currency="USD">29.99</price>
<weight units="lbs">5</weight>
<description>This is product one, and it is a beauty.</description>
</item>
<item>
<title>Product #2</title>
<price currency="USD">35.99</price>
<weight units="lbs">5.6</weight>
<description>Product two is smaller and weighs less, but is more expensive.</description>
</item>
</products>
通过添加属性,我们明确了不同产品的计量单位及货币类型。首个 XML 文档构建完毕,请注意其信息的结构化、关联性与分组逻辑。
下期教程将讲解如何创建层叠样式表,将此 XML 信息格式化以便在 Web 浏览器中查看。

