<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>
<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>
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.