XML(可扩展标记语言,Extensible Markup Language)是一种用于定义文档的规则集,使其既可被人类理解又可被机器解析。XML 由 W3C 定义,是一种用于存储和传输数据的标准格式。XML 的主要特点如下:
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note date="2024-06-01">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<br/>
数据存储:XML 可以作为数据库和应用之间的数据交换格式。
<bookstore>
<book>
<title lang="en">Harry Potter</title>
<author>J.K. Rowling</author>
<year>1997</year>
<price>29.99</price>
</book>
<book>
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
配置文件:许多软件使用 XML 文件来存储配置信息。
<configuration>
<settings>
<setting name="ServerName" value="localhost"/>
<setting name="Port" value="8080"/>
<setting name="Database" value="mydatabase"/>
</settings>
</configuration>
数据交换:XML 常用于不同系统和应用之间的数据交换。
<response>
<status>success</status>
<message>Data retrieved successfully</message>
<data>
<item id="1">
<name>Item 1</name>
<value>Value 1</value>
</item>
<item id="2">
<name>Item 2</name>
<value>Value 2</value>
</item>
</data>
</response>
Web 服务:SOAP(Simple Object Access Protocol)协议使用 XML 作为消息格式。
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:Header/>
<soap:Body>
<m:GetPrice xmlns:m="http://www.example.org/stock">
<m:StockName>IBM</m:StockName>
</m:GetPrice>
</soap:Body>
</soap:Envelope>
可以使用多种编程语言和库来解析 XML,如 Python 的 xml.etree.ElementTree
模块,Java 的 javax.xml.parsers
包等。
Python 示例:
import xml.etree.ElementTree as ET
# 解析 XML 文件
tree = ET.parse('example.xml')
root = tree.getroot()
# 遍历所有的 book 元素
for book in root.findall('book'):
title = book.find('title').text
author = book.find('author').text
print(f'Title: {title}, Author: {author}')
XML 是一种强大的数据存储和传输格式,具有良好的可扩展性和平台无关性。无论是用于配置文件、数据存储还是数据交换,XML 都提供了灵活且易于理解的解决方案。通过使用适当的工具和库,开发者可以方便地创建、解析和操作 XML 数据。
原文链接:codingdict.net