【发布时间】:2011-09-06 10:08:42
【问题描述】:
我使用以下 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) {
当然这之后还有更多代码,但我没有在这里粘贴,因为它认为它可能会更加混乱。
但我的想法是我希望从所有成员的好友列表节点中选择 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 文档进行修改。
【问题讨论】:
-
xmlDoc 是 org.w3c.Document 对象吗?
-
是的,xmlDoc 是一个常规的 org.w3c.Document 对象。
-
您使用的是 jdk 的 xpath 支持,还是其他第三方库? (例如,您的 XPath 实例的实际类名是什么)
-
我正在使用来自 JDK 的 xpath。我从不使用任何第三方库。我的 XPath 实例的类路径是 javax.xml.xpath.XPath。
-
不,不是公共 api,我的意思是 actual 实现类(例如
xpath.getClass())