Reputation: 273
I need to remove attribute from XML document by this attribute's XPath.
Everything should be done with Java.
I was able to find attribute's Node using the following code:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document document = dbf.newDocumentBuilder().parse(new File("input.xml"));
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
XPathExpression expression = xpath.compile("//div[@id='1']/@id");
Node myNode = (Node) expression.evaluate(document, XPathConstants.NODE);
My idea was to get attribute's node parent and after that call the removeChild method passing attribute's node as argument.
myNode.getParentNode().removeChild(myNode);
Unfortunately according to the API documentation attribute nodes have no parent.
How do I get the parent of an attribute Node?
Upvotes: 14
Views: 8748
Reputation:
It looks like the appropiate DOM method is
((Attr) myNode).getOwnerElement()
From http://download.oracle.com/javase/6/docs/api/org/w3c/dom/Attr.html#getOwnerElement()
The
Element
node this attribute is attached to ornull
if this attribute is not in use.
Upvotes: 24