Reputation: 2485
I have the need to search into an XML for some attributes and delete its Node if the attribute is found. For example, I want to remove the book nodes which have attributes beginning with "#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>
So far, I have been able to capture all "#false" Elements using an XPath expression:
String search = "//@*[starts-with(.,'#false')]";
NodeList nodeList = (NodeList) xPath.
compile(search).evaluate(doc, XPathConstants.NODESET);
((Node)nodeList.item(0)).getParent(); // NULL!!
However the problem is that the Parent Node of "available" Elements is null so I cannot find a way to remove the whole "book" Node. Any help ?
Upvotes: 1
Views: 1544
Reputation: 1239
you can use this xpath .. which will match with the book element itself
//*[@*[starts-with(.,'#false')]]
I hope this could help!
Upvotes: 1
Reputation: 72844
For attributes, use Attr#getOwnerElement()
to retrieve the element containing the attribute:
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();
...
}
Upvotes: 1