I am having trouble parsing an xml file and retrieve data from it. Below is the xml and code snippet. -----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>
-----Code Snippet: -----
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;
}
The code compiles OK. While running, it just doesn't seem to find the nodes "Server" and it's child "IPAddress". The call to getInput() above would come from main in the format below:
getInput("Server/IPAddress");
Not sure where it's going wrong and I am really new to Xpath. I was wondering if someone can help.
Thanks!
The outermost element is <root/>
, not <server/>
. Your query needs to be
getInput("root/Server/IPAddress")
if you want to use the full path, or even
getInput("/root/Server/IPAddress")
to indicate you're starting at the root element. Alternatively, you could have XPath to search for all server elements all over the document:
getInput("//Server/IPAddress")
All of those will output
Xpath Expression:root/Server/IPAddress
1
1
0
Node count =1;Node Name =IPAddress
instead of
Xpath Expression:Server/IPAddress
0
0
You could somehow prepend one of the prefixes of your choice in the getInput()
function, of course.
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.