user2824073
user2824073

Reputation: 2485

XPath read root element returns null

Given an XML file like:

<source>
   <element value="a">
   <element value="b">
</source>

I'm trying to read the root element ("source") of the XML using Java and XPath:

public String parseExpression(Document doc)  {
   NodeList nodeList = (NodeList) xPath.compile("/").evaluate(
                    doc, XPathConstants.NODESET);
   return nodeList.item(0).getFirstChild().getNodeValue();
}

However it returns null. Why?

Upvotes: 1

Views: 438

Answers (1)

Cfx
Cfx

Reputation: 2312

Because .getNodeValue(); does not return the value of the attribute. Try (Element)nodeList.item(0).getFirstChild()).getAttribute("value") instead. The value you are trying to read is not in the element node you are accessing. It is in a seperate attribute node which is only accessable when you cast your NodeList entry to Element.

Upvotes: 2

Related Questions