开发者

remove element in dom4j

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

I want to leav开发者_开发问答e id="2" in the dom,

how can domj4 to remove the other three ?

result:

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜