我在我的应用程序中使用 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/