[英]search for attribute in parent node and get value of Child node attribute
在父节点中搜索属性,并获取子节点的属性值。
我有一个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
。
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.