This is the code of my program i want to load xml “test” . When i build this i get loaded and no of nodes in “0”.is there is a problem in loading or x path. I am using eclipse. please help me to fix this issue.
<?xml version="1.0"?>
<resourses>
<resourse status="1">
<name>resourse1</name>
<type>1</type>
</resourse>
<resourse status="2">
<name>resourse2</name>
<type>2</type>
</resourse>
<resourse status="3">
<name>resourse3</name>
<type>3</type>
</resourse>
</resourses>
public class xml_l
{
public static void main(String[] args)
throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException
{
DocumentBuilderFactory domFactory =DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("/home/user/test/test.xml");
if (doc==null)
{
System.out.println("not loaded");
}
else
{
System.out.println(" loaded ");
}
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("//resourse[status =1]/name/text()");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
System.out.println(nodes.getLength());
for (int i = 0; i < nodes.getLength(); i++) // nodes.getLength()
{
System.out.println(nodes.item(i).getNodeValue());
}
}
}
You need to have an ‘@’ in front of the attribute to inform xPath you are looking for an attribute.
Not