Python 使用lxml.etree将整个元素移入

Python 使用lxml.etree将整个元素移入,python,xml,lxml,Python,Xml,Lxml,在lxml中,给定一个元素,是否可以将整个内容移动到xml文档中的其他位置,而不必读取它的所有子元素并重新创建它?我最好的例子就是换父母。我翻遍了一些文件,但运气不太好。提前谢谢 可以使用.append(),.insert()方法将子元素添加到现有元素中: >>> from lxml import etree >>> from_ = etree.fromstring("<from/>") >>> to = etree.froms

在lxml中,给定一个元素,是否可以将整个内容移动到xml文档中的其他位置,而不必读取它的所有子元素并重新创建它?我最好的例子就是换父母。我翻遍了一些文件,但运气不太好。提前谢谢

可以使用
.append()
.insert()
方法将子元素添加到现有元素中:

>>> from lxml import etree
>>> from_ = etree.fromstring("<from/>")
>>> to  = etree.fromstring("<to/>")
>>> to.append(from_)
>>> etree.tostring(to)
'<to><from/></to>'
来自lxml导入etree的
>>
>>>from=etree.fromstring(“”)
>>>to=etree.fromstring(“”)
>>>to.append(从\开始)
>>>etree.tostring(到)
''

.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导入etree的
>>
>>>tree=etree.XML(“”)
>>>node_b=tree.xpath('/a/b')[0]
>>>node_d=tree.xpath('/a/d')[0]
>>>节点d.附加(节点b)
>>>etree.tostring(tree)#完整的“b”-分支现在位于“d”之下,在“e”之后
''
>>>node_f=tree.xpath('/a/d/e/f')[0]#没有任何东西可以阻止我们再次移动它
>>>node_f.append(node_a)#现在'a'在'f'的下面
>>>etree.tostring(树)
''
移动具有尾部文本的节点时要小心。在lxml中,尾部文本属于节点,并随节点移动。(此外,删除节点时,其尾部文本也将被删除)

>tree=etree.XML('TAIL')
>>>node_b=tree.xpath('/a/b')[0]
>>>node_d=tree.xpath('/a/d')[0]
>>>节点d.附加(节点b)
>>>etree.tostring(树)
“尾巴”
有时这是一种理想的效果,但有时您需要这样的效果:

>>> 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>'
>tree=etree.XML('TAIL')
>>>node_b=tree.xpath('/a/b')[0]
>>>node_d=tree.xpath('/a/d')[0]
>>>node_a=tree.xpath('/a')[0]
>>>#手动移动文本
>>>node_a.text=node_b.tail
>>>node_b.tail=无
>>>节点d.附加(节点b)
>>>etree.tostring(树)
>>>#现在尾部文本保留在原来的位置
“尾巴”

正是我所需要的。谢谢类型o?:节点a应该是“node_f.append(node_a)”行上的节点b#现在“a”在“f”下面很深(也修复注释“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>'