Xpath表达式计算为空节点列表

时间:2013-10-15 14:16:57

标签: java xml xpath

我无法解析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>

----- 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;
}

代码编译正常。在运行时,它似乎没有找到节点“服务器”,它的子节点“IPAddress”。上面对getInput()的调用将来自main,格式如下:

getInput("Server/IPAddress");

不知道哪里出错了,我是Xpath的新手。我想知道是否有人可以提供帮助。

谢谢!

1 个答案:

答案 0 :(得分:1)

最外面的元素是<root/>,而不是<server/>。您的查询需要

getInput("root/Server/IPAddress")

如果你想使用完整路径,甚至

getInput("/root/Server/IPAddress")

表示你从根元素开始。或者,您可以使用XPath在整个文档中搜索所有服务器元素:

getInput("//Server/IPAddress")

所有这些都将输出

Xpath Expression:root/Server/IPAddress
1
1
0
Node count =1;Node Name =IPAddress

而不是

Xpath Expression:Server/IPAddress
0
0

当然,您可以在getInput()函数中以某种方式预先添加您选择的前缀之一。

相关问题