Wednesday, September 14, 2011

XPath Tutorial


Hi All,
Please i have small description of the XPath Parser usage in Java instead of the DOM or SAX parsers. The XPath language provides a simple, concise syntax for selecting nodes from an XML document. XPath also provides rules for converting a node in an XML document object model (DOM) tree to a boolean, double, or string value.



Below i have written  a Simple XPath Tutorial program in java
import javax.xml.xpath.*;

public static void main(String args[]){
          String xmlString = "<employees>"+
                                         "<employee> "+
"<name>"+
"Johny"+
"</name>"+
"<name>"+
"Williams"+
"</name>"+
"</employee>"+
"</employees>" ;
try{
//To get an instance of the XPathFactory object itself.

XPathFactory xPathFactory = XPathFactory.newInstance();
// Create an instance of XPath from the factory class

XPath xPath = xPathFactory.newXPath();
String expression = "/employees/employee/name";
// Compile the expression to get a XPathExpression object.
XPathExpression xpathExpression = xPath.compile(expression);
//Evaluate the expression against the XML Document to get the result.
Object result = xpathExpression.evaluate(new InputSource(new StringReader(xmlString)));


}catch(XPathExpressionException e){
e.printStackTrace();
}
}


The above program will give the name of all the employees in the xml Document.

  • If at all you need only the first employee name pass the expression value as :-

                  String expression = "/employees/employee[1]/name"; 
                  will return only the first employee name.

  • If you need to pass a document instead of an xmlString then follow the below process for reading the xml document.
       String  xmlFile = "TestFile.xml";
        Document xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
At the lat pass the only xmlDocument to evaluate() method instead of 
xmlString See Below:-
xPathExpression.evaluate(xmlDocument, returnType);
//returnType can be any of the QNames available in XPath Package:-
//XPathConstants.STRING, XPathConstants.NUMBER, XPathConstants.BOOLEAN, 
//XPathConstants.NODE and XPathConstants.NODESET. 

                              OR
      XPathReader reader = new XPathReader("src\\com\\javabeat\\tips\\xpath\\projects.xml"); 
reader.read(expression, XPathConstants.STRING)

// To get a xml attribute.
String expression = "/projects/project[1]/@id";
System.out.println(reader.read(expression, 
XPathConstants.STRING) + "\n");

// To get a child element's value.
expression = "/projects/project[2]/name";
System.out.println(reader.read(expression, 
XPathConstants.STRING) + "\n");

// To get an entire node
expression = "/projects/project[3]";
NodeList thirdProject = (NodeList)reader.read(expression,
XPathConstants.NODESET);
traverse(thirdProject);

public static void traverse(NodeList rootNode){
for(int index = 0; index < rootNode.getLength();index ++){
Node aNode = rootNode.item(index);
if (aNode.getNodeType() == Node.ELEMENT_NODE){
NodeList childNodes = aNode.getChildNodes();
if (childNodes.getLength() > 0){
System.out.println("Node Name-->" + aNode.getNodeName() +" , Node Value-->" + aNode.getTextContent());
}
traverse(aNode.getChildNodes());
}
}
}



No comments:

Post a Comment