Hi,
I am newbie for JAXP, using XML stuff from long time, but never bothered to look behind the common utilities, this time , i thought of writing my own code to handle xml related stuff, I started with XPath and got stucked in a problem and ended up writing it here.
I have this sample program, which uses JAXP to read an xml document. it works well when I am reading value of a node, but it is not returning me the nodelist or node object.
Looking for JAXP experts to help me.
Here is the code
package com.xml.xpath.test;
import java.io.File;
import java.util.Iterator;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XPathTest {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
File xmlFile = new File("Sample.xml");
// Create a DocumentBuilder
DocumentBuilder builder = factory.newDocumentBuilder();
// Parse an XML document
Document document = builder.parse(xmlFile);
XPath xPath = XPathFactory.newInstance().newXPath();
// this works gets the value of the node
System.out.println("value is " + xPath.evaluate("/catalog/journal/article[2]/title",document));
//this doesn't work doesn't give me the node
System.out.println("value is " + xPath.evaluate("/catalog/journal/article[2]/title",document,XPathConstants.NODE));
//Even getting list doesn't seems working
NodeList list = (NodeList)xPath.evaluate("/catalog/journal/article",document,XPathConstants.NODESET);
for(int i=0;i<list.getLength();i++ ) {
System.out.println(list.item(i).getChildNodes().item(0).getNodeValue());
}
}
}
Output of the program
value is Data Binding with XMLBeans1
value is [title: null]
Here the sample.xml used in this program
<?xml version="1.0" encoding="UTF-8"?>
<catalog title="OnJava.com" publisher="O'Reilly">
<journal date="January 2004">
<article>
<title>Data Binding with XMLBeans</title>
<author>Daniel Steinberg</author>
</article>
<article>
<title>Data Binding with XMLBeans1</title>
<author>Daniel Steinberg1</author>
</article>
<article>
<title>Data Binding with XMLBeans2</title>
<author>Daniel Steinberg2</author>
</article>
<article>
<title>Data Binding with XMLBeans3</title>
<author>Daniel Steinberg3</author>
</article>
<article>
<title>Data Binding with XMLBeans3</title>
<author>Daniel Steinberg3</author>
</article>
</journal>
</catalog>