Search for attribute in parent-node and get attribute-values of child-nodes.
I have the following part of a xml-File:
<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 . Now I want to look for the <param name="XXX" value="XXX_value"/>
nodes, which are the childs of my 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. Not even "Key: Value: " is printed.
How to get the values of the param
-childs if I search for include
-nodes ?
Edit 1:
System.out.println(nodeList.getLength());
delivers 1(correct)
but:
System.out.println(childList.getLength());
delivers 3 which is very weird
Edit 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.
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);
}
}
}
}
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.