MegaCleptomaniac
MegaCleptomaniac

Reputation: 133

XPath check for attribute and show the value

I need to check a bunch of .xml files for a specific permission, which is an attribute. If there is such a permission attribute i have to find out which value the attribute has.

this is my code which produces 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);
        }

    }

I guess my mistake is the NodeList but I can´t find a solution by my own.

Upvotes: 0

Views: 91

Answers (1)

Santhosh Kumar Tekuri
Santhosh Kumar Tekuri

Reputation: 3020

change:

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

to:

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

Upvotes: 1

Related Questions