java - 获取属性的节点父节点

标签 java xml dom

我需要通过此属性的 XPath 从 XML 文档中删除属性。
一切都应该用 Java 来完成。
我能够使用以下代码找到属性的节点:

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);

我的想法是获取属性的节点父节点,然后调用 removeChild 方法将属性的节点作为参数传递。

myNode.getParentNode().removeChild(myNode);

不幸的是,根据 API 文档属性节点没有父节点。

如何获取属性节点的父节点?

最佳答案

看起来合适的DOM方法是

((Attr) myNode).getOwnerElement()

来自 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.

关于java - 获取属性的节点父节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5109263/

相关文章:

java - 通过数组使用 XML 创建 JSP

java - Avro ReflectDatumWriter 中的 NullPointerException

xml - SMIL 文件 xml 对 e4x 不友好?

javascript - 我是否正确理解 react 虚拟 DOM 的意义?

java - 操作数组的内容

java - 10 秒后运行任务,除非用户按下按钮

html - OR'ing XPaths 的简写(相同的查询但多个标签类型)?

java - JAXB UnMarshal Collection 元素顺序 - 续

javascript - 在 jQuery 中结合查找/过滤功能,同时定位 DOM 元素

c# - 使用 HtmlAgilityPack 将 HTML 字符串分成两部分