简体   繁体   中英

Get attribute's Node parent

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?

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 or null if this attribute is not in use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM