我如何替换 ElementTree 中的子元素
我想根据某些标准将子元素从一棵树替换到另一棵树。我可以使用理解来做到这一点吗?但是我们如何替换ElementTree中的元素呢?
I want to replace child elements from one tree to another , based on some criteria. I can do this using Comprehension ? But how do we replace element in ElementTree?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您无法替换
ElementTree
中的元素,只能使用Element
。即使您调用
ElementTree.find()
,它也只是getroot().find()
的快捷方式。因此,您确实需要:
如果您的目标是根子元素,则提取父元素会很容易(只需调用
getroot()< /code>)否则你将不得不找到它。
You can't replace an element from the
ElementTree
you can only work withElement
.Even when you call
ElementTree.find()
it's just a shortcut forgetroot().find()
.So you really need to:
The extraction of the parent element can be easy if your target is a root sub-element (just call
getroot()
) otherwise you'll have to find it.与 DOM 不同,etree 没有显式的多文档功能。但是,您应该能够将元素从一个文档自由移动到另一个文档。您可能需要调用
_setroot这样做之后。
通过调用
insert
然后remove
,可以替换文档中的节点。Unlike the DOM, etree has no explicit multi-document functions. However, you should be able to just move elements freely from one document to another. You may want to call
_setroot
after doing so.By calling
insert
and thenremove
, you can replace a node in a document.我是Python新手,但我发现了一种狡猾的方法来做到这一点:
输入文件
input1.xml
:输入文件
input2.xml
:Python代码:(注意,混乱和hacky)
给出输出:
这是根据以下信息得出的结论:
I'm new to python, but I've found a dodgy way to do this:
Input file
input1.xml
:Input file
input2.xml
:Python code: (note, messy and hacky)
gives the output:
this was concluded with information from:
是的!使用切片语法,您可以通过理解来完成它。前任:
Yes! Using the slice syntax you can do it with comprehension. Ex: