【问题标题】:Xpath expression evaluates to an empty nodelistXpath 表达式计算结果为空节点列表
【发布时间】:2013-10-15 14:16:56
【问题描述】:

我无法解析 xml 文件并从中检索数据。下面是xml和代码sn-p。 -----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 真的很陌生。我想知道是否有人可以提供帮助。

谢谢!

【问题讨论】:

    标签: java xml xpath


    【解决方案1】:

    最外面的元素是&lt;root/&gt;,而不是&lt;server/&gt;。您的查询需要

    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() 函数中添加您选择的前缀之一。

    【讨论】:

    • 感谢您的快速帮助!那么,“Server/IPAddress”和“//Server/IPAddress”有什么区别呢?
    • 开头的/表示表达式从根节点开始; // 也可以,但会扫描整个文档(//descendant-or-self 轴)。没有斜线意味着您从当前上下文开始,这也是(如果未设置其他)根节点。
    猜你喜欢
    • 2020-07-13
    • 2012-06-04
    • 2018-11-20
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-29
    • 2015-02-15
    相关资源
    最近更新 更多