我需要搜索XML以获取某些属性,并在找到属性时删除其Node。例如,我想删除具有以"#false"
<catalog>
<book id="bk101" available="#false">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
</catalog>
到目前为止,我已经能够捕获所有&#34; #false&#34;使用XPath表达式的元素:
String search = "//@*[starts-with(.,'#false')]";
NodeList nodeList = (NodeList) xPath.
compile(search).evaluate(doc, XPathConstants.NODESET);
((Node)nodeList.item(0)).getParent(); // NULL!!
然而问题是'#34;可用的父节点&#34;元素为空,所以我找不到删除整本书的方法。节点。有什么帮助吗?
答案 0 :(得分:1)
对于属性,使用Attr#getOwnerElement()
检索包含属性的元素:
NodeList nodeList = (NodeList) xPath.
compile(search).evaluate(doc, XPathConstants.NODESET);
Node attrNode = nodeList.item(0);
if(attrNode.getNodeType() == Node.ATTRIBUTE_NODE) {
Attr attr = (Attr) attrNode;
Element bookElement = attr.getOwnerElement();
...
}
答案 1 :(得分:1)
你可以使用这个xpath ..它将与book元素本身匹配
//*[@*[starts-with(.,'#false')]]
我希望这可以提供帮助!