XPath检查属性并显示值

时间:2015-07-02 06:58:03

标签: java xml xpath

我需要检查一堆.xml文件以获取特定权限,这是一个属性。如果存在这样的权限属性,我必须找出该属性具有的值。

这是我生成NullPointerExceptions的代码:

public static void checkXmlPermissions(String path)
    {
        FileInputStream file;
        try                                                                                                 
        {
            file = new FileInputStream(new File(path));

            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); 
                                                                                                            //XPath initialisieren;
            DocumentBuilder builder =  builderFactory.newDocumentBuilder();                          

            Document xmlDocument = builder.parse(file);

            XPath xPath =  XPathFactory.newInstance().newXPath();


            String expression ="//*[@permission]";                                                                          //Expression;
            NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);

            for (int i = 0; i < nodeList.getLength(); i++) 
            {
                String match = nodeList.item(i).getFirstChild().getNodeValue();
                System.out.println(match);

            }
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }

    }

我想我的错误是NodeList但是我找不到自己的解决方案。

1 个答案:

答案 0 :(得分:1)

变化:

String match = nodeList.item(i).getFirstChild().getNodeValue();

为:

String match = nodeList.item(i).getTextContent();