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
usingDocumentHelper.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 exampleelm1.detach()
,elm2.detach()
, andelm4.detach()
. Better still make a list of those element, you want to remove, and thendetach()
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.
精彩评论