【发布时间】:2012-02-19 04:57:39
【问题描述】:
在 lxml 中,是否有可能在给定一个元素的情况下将整个内容移动到 xml 文档中的其他位置,而不必读取它的所有子元素并重新创建它?我最好的例子是改变父母。我已经翻遍了文档,但运气不佳。提前致谢!
【问题讨论】:
在 lxml 中,是否有可能在给定一个元素的情况下将整个内容移动到 xml 文档中的其他位置,而不必读取它的所有子元素并重新创建它?我最好的例子是改变父母。我已经翻遍了文档,但运气不佳。提前致谢!
【问题讨论】:
.append、.insert 和其他操作默认这样做
>>> from lxml import etree
>>> tree = etree.XML('<a><b><c/></b><d><e><f/></e></d></a>')
>>> node_b = tree.xpath('/a/b')[0]
>>> node_d = tree.xpath('/a/d')[0]
>>> node_d.append(node_b)
>>> etree.tostring(tree) # complete 'b'-branch is now under 'd', after 'e'
'<a><d><e><f/></e><b><c/></b></d></a>'
>>> node_f = tree.xpath('/a/d/e/f')[0] # Nothing stops us from moving it again
>>> node_f.append(node_a) # Now 'a' is deep under 'f'
>>> etree.tostring(tree)
'<a><d><e><f><b><c/></b></f></e></d></a>'
移动带有尾部文本的节点时要小心。在 lxml 中,尾部文本属于节点并随其移动。 (另外,当你删除一个节点时,它的尾部文本也会被删除)
>>> tree = etree.XML('<a><b><c/></b>TAIL<d><e><f/></e></d></a>')
>>> node_b = tree.xpath('/a/b')[0]
>>> node_d = tree.xpath('/a/d')[0]
>>> node_d.append(node_b)
>>> etree.tostring(tree)
'<a><d><e><f/></e><b><c/></b>TAIL</d></a>'
有时这是一个理想的效果,但有时你会需要这样的东西:
>>> tree = etree.XML('<a><b><c/></b>TAIL<d><e><f/></e></d></a>')
>>> node_b = tree.xpath('/a/b')[0]
>>> node_d = tree.xpath('/a/d')[0]
>>> node_a = tree.xpath('/a')[0]
>>> # Manually move text
>>> node_a.text = node_b.tail
>>> node_b.tail = None
>>> node_d.append(node_b)
>>> etree.tostring(tree)
>>> # Now TAIL text stays within its old place
'<a>TAIL<d><e><f/></e><b><c/></b></d></a>'
【讨论】:
您可以使用.append()、.insert() 方法将子元素添加到现有元素:
>>> from lxml import etree
>>> from_ = etree.fromstring("<from/>")
>>> to = etree.fromstring("<to/>")
>>> to.append(from_)
>>> etree.tostring(to)
'<to><from/></to>'
【讨论】: