如何删除特定标签

发布于 2024-09-07 01:09:14 字数 519 浏览 3 评论 0原文

我有以下 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

酒废 2024-09-14 01:09:14

只需调用parentNode.remove(childNode)即可。像这样的事情:

>>> etree.tostring(tree)
'<book> <bookname child="test">  <text> Works </text>  <text> Doesnt work </text>    </bookname></book>'
>>> bookname=tree[0]
>>> text2=bookname[1]
>>> bookname.remove(text2)
>>> etree.tostring(tree)
'<book> <bookname child="test">  <text> Works </text>  </bookname></book>'
>>>

在这里,我获取书名节点并要求它删除它的第二个子节点。

为了查找要删除的节点,我将使用 xpath

Just call parentNode.remove(childNode). Something like this:

>>> etree.tostring(tree)
'<book> <bookname child="test">  <text> Works </text>  <text> Doesnt work </text>    </bookname></book>'
>>> bookname=tree[0]
>>> text2=bookname[1]
>>> bookname.remove(text2)
>>> etree.tostring(tree)
'<book> <bookname child="test">  <text> Works </text>  </bookname></book>'
>>>

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文