How can I remove all selected nodes from an XPath?

advertisements

I run an XPath in Java with the following xml and code:

<?xml version="1.0" encoding="UTF-8"?>
<list>
    <member name="James">
        <friendlist>
            <friend>0001</friend>
            <friend>0002</friend>
            <friend>0003</friend>
        </friendlist>
    </member>
    <member name="Jamie">
        <friendlist>
            <friend>0003</friend>
            <friend>0002</friend>
            <friend>0001</friend>
        </friendlist>
    </member>
    <member name="Katie">
        <friendlist>
            <friend>0001</friend>
            <friend>0003</friend>
            <friend>0004</friend>
        </friendlist>
    </member>
</list>

Code:

try {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression pathExpr = xpath.compile("/list/member/friendlist/friend[.='0003']");
} catch (XPathExpressionException e) {

Of course there are more codes after this but I didn't paste it here because it thought it may confuse even more.

But the idea is I wish to select all the friend nodes that have the ID 0003 from all the members' friendlist nodes, and then remove it from the XML file. The XPath works by selecting all the "friend" nodes that have the value=0003. I know I can use the removeChild() method of the XML Document object. But the problem is how do I remove all of it directly, without going through layers of loops starting from its parent? The removeChild() method needs me to know its parent's parent's parent.

Thanks!

Update: This is how I used my XPath:

XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression pathExpr = null;
try {
    pathExpr = xpath.compile("/list/member/friendlist/friend[.='0003']");
} catch (XPathExpressionException e) {
    e.printStackTrace();
}
NodeList list = null;
try {
    list = (NodeList) pathExpr.evaluate(xmlDoc, XPathConstants.NODESET);
} catch (XPathExpressionException e) {
    e.printStackTrace();
}

The xmlDoc is an XML document object that has an XML file parsed. The XML works fine. It is only the XML not returning a reference but a whole new nodelist, which makes it impossible for me to refer back to its original xml document to do amendments.


for each node in the returned NodeList:

n.getParentNode().removeChild(n);