selectSingleNode returns null
843834Aug 22 2005 — edited Aug 22 2005Hi
I'm quite new to xpath. I have an xml file and in my basic code I was able to get the node values and their attributes using selectSingleNode and getNodeValue functions.
But in my code I return a node using selectSingleNode. Then I try to get the value of an element and its attribute in the node value that was returned and I get null. See code below.
Please let me know what I am missing.
Thanks in advance.
XML file
----------
<?xml version="1.0" encoding="UTF-8"?>
<moving_object>
<vehicle>
<car>
<honda>
<sedan engine="v6">
</honda>
</car>
</vehicle>
</moving object>
Java file
-----------
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import org.apache.xpath.XPathAPI;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
public class moving
{
String fileName = "moving.xml";
public static void main(String[] args)
{
Document document = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
Node rootNode = null;
Node subNode = null;
Node subNode2 = null;
String str = null;
try
{
builder = factory.newDocumentBuilder();
document = builder.parse( new File(fileName));
rootNode = (Node) document.getDocumentElement();
System.out.println("RootNode :" + rootNode);
subNode1 = XPathAPI.selectSingleNode(rootNode, "/moving_object/vehicle");
System.out.println("SubNode1 :" + subNode1);
subNode2 = XPathAPI.selectSingleNode(subNode1,"/vehicle/car/honda/sedan/@engine");
System.out.println("SubNode2 :" + subNode2);
str = XPathAPI.selectSingleNode(subNode1,"/vehicle/car/honda/sedan/@engine").getNodeValue();
System.out.println("Engine power is " + str);
}
catch (ParserConfigurationException e)
{
e.printStackTrace();
} catch (SAXException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
} catch (TransformerException e)
{
e.printStackTrace();
}
}
}
Output
---------
RootNode :<moving_object>
<vehicle>
<car>
<honda>
<sedan engine="v6" />
</honda>
</car>
</vehicle>
</moving_object>
SubNode1 :<vehicle>
<car>
<honda>
<sedan engine="v6" />
</honda>
</car>
</vehicle>
SubNode2 :null
java.lang.NullPointerException
at moving.main(moving.java:62)
Exception in thread "main"