简体   繁体   English

使用lxml.etree移动整个元素

[英]Move an entire element in with lxml.etree

Within lxml, is it possible, given an element, to move the entire thing elsewhere in the xml document without having to read all of it's children and recreate it? 在lxml中,在给定元素的情况下,是否有可能将整个内容移动到xml文档中的其他位置,而无需读取所有子项并重新创建它? My best example would be changing parents. 我最好的例子就是改变父母。 I've rummaged around the docs a bit but haven't had much luck. 我有点翻遍文档,但运气不好。 Thanks in advance! 提前致谢!

.append , .insert and other operations do that by default .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>'

Be careful when moving nodes having a tail text. 移动具有尾部文本的节点时要小心。 In lxml tail text belong to the node and moves around with it. 在lxml尾部文本属于节点并随之移动。 (Also, when you delete a node, its tail text is also deleted) (另外,当您删除节点时,其尾部文本也会被删除)

>>> 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>'

Sometimes it's a desired effect, but sometimes you will need something like that: 有时这是一种理想的效果,但有时你需要这样的东西:

>>> 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>'

You could use .append() , .insert() methods to add a subelement to the existing element: 您可以使用.append() .insert()方法将子元素添加到现有元素:

>>> from lxml import etree
>>> from_ = etree.fromstring("<from/>")
>>> to  = etree.fromstring("<to/>")
>>> to.append(from_)
>>> etree.tostring(to)
'<to><from/></to>'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM