如何删除特定标签
我有以下 XML 文件:
<book>
<bookname child="test">
<text> Works </text>
<text> Doesn't work </text>
</bookname>
</book>
这只是一个块,有多个
标签。我需要遍历整个文档并删除特定的
标签。我该怎么做?
我的方法是首先创建一个 ElementTree
,然后使用 ElementTree.getroot()
获取一个 Element
实例。然后我使用 Element.clear()。这个方法可以吗?我本来想使用 Element.remove() ,但我无法让它工作。任何人都可以为我提供示例语法。
谢谢您的帮助!
I have the following XML file:
<book>
<bookname child="test">
<text> Works </text>
<text> Doesn't work </text>
</bookname>
</book>
This is just a one block, there are more than one <bookname>
tags. I need to iterate through the whole document and remove specific <text>
tags. How do I do that?
My approach is to create an ElementTree
first and then get an Element
instance using ElementTree.getroot()
. Then I use Element.clear()
. Is this approach ok? I had want to use Element.remove()
but I can't get it to work. Can anyone provide me with a sample syntax.
Thank you for the help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需调用parentNode.remove(childNode)即可。像这样的事情:
在这里,我获取书名节点并要求它删除它的第二个子节点。
为了查找要删除的节点,我将使用 xpath
Just call
parentNode.remove(childNode)
. Something like this:Here I take the bookname node and ask it to remove it's second child.
For finding the nodes you want to remove, I'd use xpath