1

我无法解析 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 真的很陌生。我想知道是否有人可以提供帮助。

谢谢!

4

1 回答 1

2

最外层的元素是<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()当然,您可以以某种方式在函数中添加您选择的前缀之一。

于 2013-10-15T15:37:13.033 回答