java - XPath 检查属性并显示值

标签 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,但我自己找不到解决方案。

最佳答案

更改:

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

至:

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

关于java - XPath 检查属性并显示值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31177560/

相关文章:

python - 只解析 XML 文件的特定子树

PHP 简单 XML : insert node at certain position

xslt - 使用xslt获取X位置的节点值

css - 将谓词应用于xpath中的字符串为何有效?

java - 分层死锁(具有依赖性),...或 : how do I get my "wait"s, "notify"s,设计对吗?

java - JTree:可变行高

java - 带有限定符 @SystemProperty 的 String 类型的依赖关系不满足

Java 泛型和向上转型

xml - XSLT 将元素移动到另一个节点并在移动之前删除一些子元素

c++ - 解析 xpath 表达式