Delete XML node based on position in Java
I have an XML file like this:
<A>
<B>
<c>1<c/>
<d>2<d/>
<e>3<e/>
</B>
<B>
<c>11<c/>
<d>22<d/>
<e>33<e/>
</B>
</A>
Say I wanted to delete the second node. How would I do this?
I have not written code to do this yet. I've researched online but was not able to find just what I'm looking to do. My program lists the items 开发者_开发问答in a jtable and it needs to let you select the item and hit a delete button.
I've implemented everything except the deletion, but there is too much and nothing really relevant.
You can find it with the XPath expression /A/B[2]
.
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression compiledExp = xPath.compile("/A/B[2]");
Node foundNode = (Node)compiledExp.evaluate(doc, XPathConstants.NODE);
then use:
foundNode.getParentNode().removeChild(foundNode);
to delete it
精彩评论