我无法解析 xml 文件并从中检索数据。下面是xml和代码片段。-----XML(test.xml)-----
<?xml version="1.0" encoding="utf-8"?>
<root>
<Server>
<IPAddress>xxx.xxx.xxx.xxx</IPAddress>
<UserName>admin</UserName>
<Password>admin</Password>
</Server>
-----代码片段: -----
public static String getInput(String element)
{
String value = "";
try {
File inputFile = new File("test.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbFactory.newDocumentBuilder();
Document inputData = builder.parse(inputFile);
inputData.getDocumentElement().normalize();
String[] elementArray = element.split("/");
XPath xPath = XPathFactory.newInstance().newXPath();
String xpathExpression = element;
System.out.println("Xpath Expression:" + xpathExpression);
NodeList node = (NodeList) xPath.compile(xpathExpression).evaluate(inputData, XPathConstants.NODESET);
System.out.println(node.getLength());
if (null != node){
System.out.println(node.getLength());
for (int i=0; i<node.getLength(); i++){
System.out.println(i);
System.out.println("Node count =" + node.getLength() + ";" +
"Node Name =" + node.item(i).getNodeName());
if (node.item(i).getNodeName() == elementArray[1]){
System.out.println(node.item(i).getNodeName()+ "=" + node.item(i).getNodeValue());
value = node.item(i).getNodeValue();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
代码编译正常。在运行时,它似乎没有找到节点“服务器”并且它是子节点“IPAddress”。上面对 getInput() 的调用将来自以下格式的 main:
getInput("Server/IPAddress");
不知道哪里出了问题,我对 Xpath 真的很陌生。我想知道是否有人可以提供帮助。
谢谢!