【发布时间】:2015-07-13 08:03:01
【问题描述】:
短版:
在父节点中搜索属性并获取子节点的属性值。
加长版:
我有一个 xml 文件的以下部分:
<include template="directory/file.xml">
<param name="permission" value="permission_value"/>
<param name="path" value="path_value"/>
</include>
我使用 xPath-request "//include[@template]" 检查整个文件并收到一个 nodelist 。现在我想查找 <param name="XXX" value="XXX_value"/> 节点,它们是我的 xPath-result-nodes 的子节点。
[initialize xPath before...]
String expression ="//include[@template]";
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
if(nodeList.getLength()>0)
{
for(int i=0; i<nodeList.getLength(); i++)
{
NodeList childList = nodeList.item(i).getChildNodes();
for(int k=0; k<childList.getLength(); k++)
{
// System.out.println(childList.item(k).getNodeName()); --> prints "#text"
String name = childList.item(k).getAttributes().getNamedItem("name").toString().replace("\"", "").replace("name=", "");
String value = childList.item(k).getAttributes().getNamedItem("value").toString().replace("\"", "").replace("value=", "");
System.out.println("Key: "+key+" Value: "+value);
}
}
}
但是这段代码对我不起作用,因为目前除了带有“#text”输出的注释之外根本没有输出。甚至没有打印“键:值:”。
如果我搜索include-nodes,如何获取param-childs 的值?
编辑 1:
System.out.println(nodeList.getLength());
提供 1(正确)
但是:
System.out.println(childList.getLength());
提供了 3 个,这很奇怪
编辑 2:
似乎他无法获得属性。我尝试使用
获取属性String key = childList.item(k).getAttributes().getNamedItem("name").toString(); 并在此行收到 NullPointerException。
【问题讨论】:
-
你能告诉我们输出是什么吗?如果有的话。我看不出“我”是从哪里来的。我觉得应该是0?而且我认为 getNamedItem 返回属性的值,因此您不必替换所有这些字符。
-
根本没有输出。
-
你能给我们更多的信息吗?我想知道'nodeList.getLength'的值以及你为什么使用'i'?
-
@cvesters 解决了这个问题。 i 来自另一个 for 循环
-
ChildList.item(k).getNodeType.equals(Node. ELEMENT_NODE)