删除 dom4j 中的元素

发布于 2024-08-13 00:25:33 字数 268 浏览 3 评论 0原文

<root>
 <elm id="1"/>
 <elm id="2"/>
 <elm id="3"/>
 <elm id="4"/>
</root>

我想在 dom 中留下 id="2",
domj4如何删除其他三个?

结果:

<root>
 <elm id="2"/>
</root>
<root>
 <elm id="1"/>
 <elm id="2"/>
 <elm id="3"/>
 <elm id="4"/>
</root>

I want to leave id="2" in the dom,
how can domj4 to remove the other three ?

result:

<root>
 <elm id="2"/>
</root>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

远山浅 2024-08-20 00:25:33

到目前为止你做了什么?好吧,我会从头开始。

  • 尝试使用 DocumentHelper.parseText(xmlStr) 获取 Document

  • 然后使用 Document.getRootElement() 获取文档的根元素

  • 获取根元素后,可以使用Element.getElements()或其变体循环遍历所有子元素,并使用Element.getAttributes()检查每个元素的属性 或其变体。

  • 确定所有三个元素后,这三个元素不是必需的。您可以使用 detach() 方法从文档中删除它们。例如,elm1.detach()elm2.detach()elm4.detach()。最好还是制作一个要删除的元素的列表,然后在循环中detach()

干杯。

注意:如果元素不是直接子元素,Document.remove(Element elem) 方法将不起作用。有关更多信息,请参阅文档

What have you done so far? Well, I would go from the scratch.

  • Try to get the Document using DocumentHelper.parseText(xmlStr)

  • Then get the root element of the document using Document.getRootElement()

  • After getting the root element, you can loop through all child elements using Element.getElements() or its variants, and check the attributes of each element using Element.getAttributes() or its variants.

  • After determining all three elements, which are not required. You can use detach() method to remove those from the document. For example elm1.detach(), elm2.detach(), and elm4.detach(). Better still make a list of those element, you want to remove, and then detach() in a loop.

Cheers.

NOTE: Document.remove(Element elem) method will not work if the element is not the immediate child. For more see the docs.

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