用Python处理XML文档有没有简单的方法?

7 投票
2 回答
7224 浏览
提问于 2025-04-17 05:25

我对这个问题做了一些研究,但还没找到什么有用的东西。我需要的不仅仅是解析和读取XML文档,而是能够在Python中像JavaScript那样操作HTML文档。

让我举个例子。假设我有以下这个XML文档:

<library>
    <book id=123>
        <title>Intro to XML</title>
        <author>John Smith</author>
        <year>1996</year>
    </book>
    <book id=456>
        <title>XML 101</title>
        <author>Bill Jones</author>
        <year>2000</year>
    </book>
    <book id=789>
        <title>This Book is Unrelated to XML</title>
        <author>Justin Tyme</author>
        <year>2006</year>
    </book>
</library>

我需要一种方法来获取某个元素,可以使用XPath或者一种“Python风格”的方法,具体可以参考这里,但我还需要能够对文档进行操作,比如下面这样:

>>>xml.getElement('id=123').title="Intro to XML v2"
>>>xml.getElement('id=123').year="1998"

如果有人知道Python中有没有这样的工具,请告诉我。谢谢!

2 个回答

15

如果你不想安装 lxml.etree,可以使用标准库里的 xml.etree

这里是 Acorn的回答,已经转换成了 xml.etree 的用法:

import xml.etree.ElementTree as et  # was: import lxml.etree as et

xmltext = """
<root>
    <fruit>apple</fruit>
    <fruit>pear</fruit>
    <fruit>mango</fruit>
    <fruit>kiwi</fruit>
</root>
"""

tree = et.fromstring(xmltext)

for fruit in tree.findall('fruit'): # was: tree.xpath('//fruit')
    fruit.text = 'rotten %s' % (fruit.text,)

print et.tostring(tree) # removed argument: prettyprint

注意: 如果我能以清晰的方式在Acorn的回答下留言,我会这样做。如果你喜欢这个回答,请给Acorn点赞。

13

lxml 是一个库,它可以让你用 XPath 选择网页中的元素,还可以对这些元素进行操作。

import lxml.etree as et

xmltext = """
<root>
    <fruit>apple</fruit>
    <fruit>pear</fruit>
    <fruit>mango</fruit>
    <fruit>kiwi</fruit>
</root>
"""

tree = et.fromstring(xmltext)

for fruit in tree.xpath('//fruit'):
    fruit.text = 'rotten %s' % (fruit.text,)

print et.tostring(tree, pretty_print=True)

结果:

<root>
    <fruit>rotten apple</fruit>
    <fruit>rotten pear</fruit>
    <fruit>rotten mango</fruit>
    <fruit>rotten kiwi</fruit>
</root>

撰写回答