在特定位置从xml删除节点

时间:2011-11-24 08:43:50

标签: java xpath jaxp

我有如下XML:

<As>
<a>
    <Bs>
        <b>5</b>
    <Bs>
</a>
<a>
    <Bs>
        <b>9</b>
    <Bs>
</a>
<a></a>
<a>
    <Bs>
        <b>12</b>
        <b>14</b>
        <b>15</b>
    </Bs>
</a>

现在我要删除节点选择的行。假设用户已选择节点<b>14</b>

我已将表达式生成为:

String expression  =  "/As/a[4]/Bs/b[2]";
Node node = (Node) xpath.evaluate(expression, doc, XPathConstants.NODE);
node.getParentNode().removeChild(node);

它给出了以下例外:

javax.xml.transform.TransformerException: Extra illegal tokens: 'health-history-questions', '/', 'health-history-question', '[', '3', ']'
at org.apache.xpath.compiler.XPathParser.error(XPathParser.java:610)
at org.apache.xpath.compiler.XPathParser.initXPath(XPathParser.java:145)
at org.apache.xpath.XPath.<init>(XPath.java:178)
at org.apache.xpath.XPath.<init>(XPath.java:266)
at org.apache.xpath.jaxp.XPathImpl.eval(XPathImpl.java:195)
at org.apache.xpath.jaxp.XPathImpl.evaluate(XPathImpl.java:281)

2 个答案:

答案 0 :(得分:1)

抱歉伙计问题是......表达式表单缺少'/'。所以我的错误。我道歉。

答案 1 :(得分:0)

为什么要使用这么复杂的XPath?试试这个

String expression = "//b[.=14]";

或者,如果你必须检查正确的层次结构,那么这个:

String expression = "/As/a/Bs/b[.=14]";