python - 有没有一种简单的方法可以在 Python 中操作 XML 文档?

标签 python xml

我已经围绕这个问题做了一些研究,但还没有真正想出任何有用的东西。我需要的不仅仅是解析和读取,而是实际在 python 中操作 XML 文档,类似于 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 也可以使用“pythonic”方法来检索元素的方法,如 here 所述,但我还需要能够操作文档,如下所示:

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

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

最佳答案

如果你想避免安装lxml.etree,你可以使用xml.etree来自标准库。

这里是 Acorn's answer移植到 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 点赞。

关于python - 有没有一种简单的方法可以在 Python 中操作 XML 文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7967082/

相关文章:

python - matplotlib.pyplot 文档说它是 matplotlib 的基于状态的接口(interface)。什么是基于状态的接口(interface)?

python - Xpath 返回的内容超出了预期(python、urllib、lxml)

python - UDP 服务器和 UDP 客户端之间的区别 : sock. bind((host, port)) 是在客户端还是服务器端?

xml - 深度优先读取大型 XML 文件

SQL 查询具有多个子元素的分层 XML

sql - 在关系数据库中存储 XML 数据的常见问题是什么?

excel - VBA XML V6.0 如何让它等待页面加载?

python - pycurl/curl 不遵循 CURLOPT_TIMEOUT 选项

python - 无法在此数据源中查找

java - 新的二进制 XML 文件行 #19 : Error inflating class activity