[英]search for attribute in parent node and get value of Child node attribute
Search for attribute in parent-node and get attribute-values of child-nodes. 在父节点中搜索属性,并获取子节点的属性值。
I have the following part of a xml-File: 我有一个xml文件的以下部分:
<include template="directory/file.xml">
<param name="permission" value="permission_value"/>
<param name="path" value="path_value"/>
</include>
I check the whole file with the xPath-request "//include[@template]"
and recive a nodelist . 我用xPath-request
"//include[@template]"
检查整个文件,并获取一个nodelist。 Now I want to look for the <param name="XXX" value="XXX_value"/>
nodes, which are the childs of my xPath-result-nodes. 现在,我要查找
<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);
}
}
}
But this code doesn´t work for me beacause currently there is no output at all apart of the comment with the "#text" output. 但是此代码对我不起作用,因为当前注释输出为“ #text”时根本没有输出。 Not even "Key: Value: " is printed.
甚至没有打印“键:值:”。
How to get the values of the param
-childs if I search for include
-nodes ? 如果我搜索
include
-nodes,如何获取param
-childs的值?
Edit 1: 编辑1:
System.out.println(nodeList.getLength());
delivers 1(correct) 提供1(正确)
but: 但:
System.out.println(childList.getLength());
delivers 3 which is very weird 提供3个,这很奇怪
Edit 2: 编辑2:
It seems like if he can´t get the attributes. 好像他无法获得这些属性。 I tried to get the attributes with
我试图用
String key = childList.item(k).getAttributes().getNamedItem("name").toString();
and recived a NullPointerException
at this line. 并在此行获取
NullPointerException
。
String expression ="//include[@template]";
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for(int i=0; i<nodeList.getLength(); i++){
NodeList childList = nodeList.item(i).getChildNodes();
for(int k=0; k<childList.getLength(); k++){
Node child = childList.item(k);
if(child instanceof Element){
Element elem = (Element)child;
if("param".equals(elem.getLocalName())){
String name = elem.getAttribute("name");
String value = elem.getAttribute("value");
System.out.println("Name: "+name+" Value: "+value);
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.