python-2.7 - lxml - 无法替换 child 的 child

标签 python-2.7 xpath lxml lxml.objectify

我在我的应用程序中使用 lxml 作为 XML 解析的解决方案。

我知道 lxml 只能替换父级的直接子级,但不能使用 .replace 替换该子级下的级别

示例 XML:

<root>

    <dc>

        <batman alias='dark_knight' />

    </dc>

</root>

我在这样的字符串中修改了标签

<batman alias='not_dark_knight' />

我需要一些帮助来使用 xpath '/root/dc/batman' 替换原始 XML。

from lxml import etree

original_xml = "<root><dc><batman alias='dark_knight' /></dc></root>"
modified_tag = "<batman alias='not_dark_knight' />"
x_path = '/root/dc/batman'
original_obj = etree.fromstring(original_xml)
modified_obj = etree.fromstring(modified_tag)

original_obj.replace(original_obj.xpath(x_path)[0], modified_obj)

这会抛出一个ValueError: Element is not a child of this node. 有没有办法可以很好地替换字符串? (仅使用 lxml)

请理解,我想要一个仅使用 lxml 库的解决方案。

最佳答案

如您所知,您应该在要替换的元素的父级 上调用replace()。您可以使用 .getparent() 动态获取父级:

batman = original_obj.xpath(x_path)[0]
batman.getparent().replace(batman, modified_obj)

关于python-2.7 - lxml - 无法替换 child 的 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42538591/

相关文章:

python - 无法使用 lxml Xpath 解析器解析 html

python-2.7 - 使用 pytest-allure-adaptor 自定义 Allure 报告

python - 如何用样本列表计算字符串中的字母数?

python - 在 Python 2.7 中保存/加载大型列表的最快方法是什么?

python - 如何在Python脚本中将随机参数传递给另一个Python程序?

css - 使用 XPath 和 CSS 定位元素

XSLT:reocurring xpath的缩写

python - 用python解析xml中的CDATA

xml - 为什么 < 不转换为 < while > 和其他转义字符适当转换

python - 在python中等待xml文件写入完成