在 Python 中,你可以使用不同的库来解析 XML 数据,其中最常用的是 xml.etree.ElementTree 模块。以下是一个简单的例子,演示如何使用这个模块来解析 XML 数据:

1. 导入模块
import xml.etree.ElementTree as ET

2. 解析 XML 字符串
xml_string = """
<bookstore>
  <book>
    <title>Introduction to Python</title>
    <author>John Doe</author>
    <price>29.99</price>
  </book>
  <book>
    <title>Python Cookbook</title>
    <author>Jane Smith</author>
    <price>39.95</price>
  </book>
</bookstore>
"""

# 解析 XML 字符串
root = ET.fromstring(xml_string)

3. 遍历 XML 元素
# 遍历 book 元素
for book_element in root.findall("book"):
    title = book_element.find("title").text
    author = book_element.find("author").text
    price = book_element.find("price").text
    print(f"Title: {title}, Author: {author}, Price: {price}")

4. 解析 XML 文件
# 保存 XML 内容到文件
with open("books.xml", "w") as file:
    file.write(xml_string)

# 解析 XML 文件
tree = ET.parse("books.xml")
root = tree.getroot()

5. 修改 XML 元素
# 修改第一本书的价格
first_book_price_element = root.find("book/price")
first_book_price_element.text = "19.99"

# 添加新书
new_book_element = ET.Element("book")
new_title_element = ET.Element("title")
new_author_element = ET.Element("author")
new_price_element = ET.Element("price")

new_title_element.text = "Advanced Python Programming"
new_author_element.text = "Bob Johnson"
new_price_element.text = "49.99"

new_book_element.append(new_title_element)
new_book_element.append(new_author_element)
new_book_element.append(new_price_element)

root.append(new_book_element)

注意事项

  •  在实际应用中,XML 数据通常来自文件或网络请求,而不是硬编码在脚本中。

  •  注意处理 XML 中的命名空间,如果 XML 中使用了命名空间,需要使用带有命名空间的元素名来查找。

  •  对于更复杂的 XML 操作,也可以考虑使用 lxml 库,它提供了更丰富的功能和更高的性能。


这只是一个简单的 XML 解析的例子,根据实际需求可能需要更复杂的操作和处理。


转载请注明出处:http://www.zyzy.cn/article/detail/13342/Python 基础