如何从XPath中删除所有选定的节点?

时间:2011-06-01 15:33:28

标签: java xml xpath

我使用以下xml和代码在Java中运行XPath:

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

代码:

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

当然在此之后会有更多代码,但我没有将其粘贴到此处,因为它认为它可能会更加混乱。

但我的想法是希望从所有成员的friendlist节点中选择具有ID 0003的所有朋友节点,然后将其从XML文件中删除。 XPath通过选择值为0003的所有“朋友”节点来工作。我知道我可以使用XML Document对象的removeChild()方法。但问题是我如何直接删除所有这些,而不从其父级开始循环层? removeChild()方法需要我知道它的父节点的父节点。

谢谢!

更新: 这就是我使用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();
}

xmlDoc是一个XML文档对象,它解析了XML文件。 XML工作正常。只有XML不返回引用而是返回一个全新的节点列表,这使我无法返回其原始的xml文档进行修改。

3 个答案:

答案 0 :(得分:10)

返回的NodeList中的每个节点:

n.getParentNode().removeChild(n);

答案 1 :(得分:3)

我不明白为什么返回的nodelist节点为parentNode()返回null。

但您可以尝试首先使用此XPath表达式选择要删除的节点的所有父节点:

"/list/member/friendlist[friend[.='0003']]"

或同等的,

"/list/member/friendlist[friend = '0003']]"

然后遍历生成的节点列表,并在每个节点的上下文中查询与XPath表达式匹配的节点

"friend[.='0003']"

这将为您提供一个父节点和一个与removeChild()一起使用的子节点。

答案 2 :(得分:1)

查看XUpdate。它不漂亮,但它有效。