在父节点中搜索属性并获取子节点的属性值。
我有xml-File的以下部分:
<include template="directory/file.xml">
<param name="permission" value="permission_value"/>
<param name="path" value="path_value"/>
</include>
我使用xPath-request "//include[@template]"
检查整个文件并重新获取节点列表。现在我想查找<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”输出的注释之外根本没有输出。甚至不打印“Key:Value:”。
如果我搜索param
- 节点,如何获取include
- 孩子的值?
修改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 :(得分:1)
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);
}
}
}
}