我有以下XML文件:的XPath - 从父元素获取id属性
<diagnostic version="1.0">
<!-- diagnostic panel 1 -->
<panel xml:id="0">
<!-- list controls -->
<control xml:id="0_0">
<settings description="text 1"/>
</control>
<control xml:id="0_1">
<settings description="text 2"/>
</control>
</panel>
<panel xml:id="1">
<!-- list controls -->
<control xml:id="1_0">
<settings description="text 3"/>
</control>
<control xml:id="1_1">
<settings description="text 4"/>
</control>
</panel>
</diagnostic>
和定义的XPath:
//*[not(@description='-')]/@description
和Java代码:
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("diagnostic.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
// XPath Query for showing all nodes value
XPathExpression expr = xpath.compile("//*[not(@description='-')]/@description");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(i + ": " + nodes.item(i).getParentNode() + nodes.item(i).getNodeValue());
}
的XPath的定义会返回所有属性值说明其中值这个属性不是' - '。
输出:
text 1
text 2
text 3
text 4
但我需要找到这个属性描述也属性XML:ID元素控制。
输出:
0_0 text 1
0_1 text 2
1_0 text 3
1_1 text 4
如何做,在我的描述也返回XML:ID 控制的元素?我需要知道给定元素的描述控制。
这也想到了我,但问题是getParentNode()返回null。 – Martin
也许元素不被认为是属性的父节点?他可以获取设置元素并手动获取描述属性。 –