Amazing technological breakthrough possible @S-Logix pro@slogix.in

Office Address

  • #5, First Floor, 4th Street Dr. Subbarayan Nagar Kodambakkam, Chennai-600 024 Landmark : Samiyar Madam
  • pro@slogix.in
  • +91- 81240 01111

Social List

How to evaluate xpath expression in xml file using java?

Description

Sample code given below parse the xml file named healthRecord.xml and evaluates the xpath expression. Related xpath expressions are commented and uncomment of those expressions will provide the required result.

Sample Code
  • Filename: XML_XpathTest.java

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;
import org.w3c.dom.*;
import javax.xml.xpath.XPathConstants;
import java.io.*;

class XML_XpathTest {
public static void main(String args[]) {
try {
XPathFactory factory = XPathFactory.newInstance( );
XPath xPath = factory.newXPath( );
String expression= "//*";
//expression= "/healthrecord/hospital/lung_disease/attribute::p_id";
//expression= "/healthrecord/hospital";
//expression= "/healthrecord";
//expression= "healthrecord/hospital";
//expression= "//hospital";
//expression= "healthrecord//hospital";
//expression= "//@p_id";
//expression= "//*";

NodeList shows = (NodeList) xPath.evaluate(expression,new InputSource(new FileReader("healthRecord.xml")),XPathConstants.NODESET);
System.out.println("Document has " + shows.getLength( ) + " nodes.");
for (int i = 0; i < shows.getLength(); i++)
{
String s1=shows.item(i).getNodeName();
System.out.println("Node Name:"+s1+" "+"\n");
String sout ="Node Name:"+s1+" "+"\n";
String s2=shows.item(i).getNodeValue();
}
}
catch(Exception e) {
System.out.println(e);
}
}
}

  • Filename: healthRecord.xml

<healthrecord>

<hospital c_name="JK Hospital">

<lung_disease p_id="1" p_name="Karthik">Flu</lung_disease>

<lung_disease p_id="2" p_name="Jeeva">Pneumonia</lung_disease>

<digestive_disease p_id="3" p_name="Ravi">Gastrics</digestive_disease>

<digestive_disease p_id="4" p_name="Geetha">StomachCancer</digestive_disease>

</hospital>

<hospital c_name="KMC Hospital">

<lung_disease p_id="1" p_name="Praveen">Bronchitis</lung_disease>

<lung_disease p_id="2" p_name="Dilshanth">Flu</lung_disease>

<digestive_disease p_id="3" p_name="Deepa">StomachCancer</digestive_disease>

<digestive_disease p_id="4" p_name="Nasreen">GastricUlcer</digestive_disease>

</hospital>

</healthrecord>

Screenshots

Evaluate xpath expression in xml file using java