我正在玩一个在@ http://www.jsphylosvg.com/examples/source.php?example=2&t=xml 找到的 xml 文件
如果节点的值为 name="Espresso"
,我想插入一个节点。
例如我想更改为:
<clade>
<name>Espresso</name>
<branch_length>2.0</branch_length>
</clade>
到:
<clade>
<name>Espresso</name>
<url>www.espresso.com</url>
<branch_length>2.0</branch_length>
</clade>
根据我迄今为止所做的研究,我可以使用 xpath
找到包含 espresso 的节点(这应该可行,但实际上不行?)
import re, sys
import lxml.etree
f = open("test.xml", "r")
data = f.read()
tree = lxml.etree.XML(data)
if tree.xpath('//name/text()="Espresso"'):
insert new child here
此时,应该可以使用lxml.etree.Element
来制作xml节点,并使用insert将它们附加到xml文档中
然而,虽然这在理论上听起来不错,但我无法让它发挥作用。
我真的很感激任何帮助/建议
最佳答案
您的 XPath 语句不完全正确。这就是我认为您想要的:
>>> DOC = """<clade>
... <name>Espresso</name>
... <branch_length>2.0</branch_length>
... </clade>"""
>>>
>>> import lxml.etree
>>> tree = lxml.etree.XML(DOC)
>>> matches = tree.xpath('//name[text()="Espresso"]')
然后在匹配后追加元素:
>>> for e in matches:
... sibling = lxml.etree.Element("url")
... sibling.text = "www.espresso.com"
... e.addnext(sibling)
>>> print lxml.etree.tostring(tree)
<clade>
<name>Espresso</name><url>www.espresso.com</url>
<branch_length>2.0</branch_length>
</clade>
编辑:
由于您的文档有一个命名空间,您希望将一个命名空间映射传递给 XPath 函数并在标记名称前加上命名空间前缀,如下所示:
>>> nsmap = {'phylo': 'http://www.phyloxml.org'}
>>> tree.xpath('//phylo:name[text()="Espresso"]', namespaces=nsmap)
[<Element {http://www.phyloxml.org}name at 0x2c875f0>]
关于python - 如何根据文本节点的值添加一个xml节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11927298/