import
java.io.File;
import
javax.xml.parsers.DocumentBuilder;
import
javax.xml.parsers.DocumentBuilderFactory;
import
javax.xml.xpath.XPath;
import
javax.xml.xpath.XPathConstants;
import
javax.xml.xpath.XPathExpression;
import
javax.xml.xpath.XPathExpressionException;
import
javax.xml.xpath.XPathFactory;
import
org.w3c.dom.Document;
import
org.w3c.dom.NodeList;
public
class
XPathDemo {
public
static
void
main(String[] args)
throws
Exception
{
File xmlFile =
new
File(
"student.xml"
);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document xml = db.parse(xmlFile);
xml.getDocumentElement().normalize();
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
String name = (String)xpath.evaluate(
"/students/student[2]/name"
, xml,
XPathConstants.STRING);
System.out.println(
"2nd Student Name: "
+ name);
NodeList nodes = (NodeList)xpath.evaluate(
"/students/student[@branch = \"IT\"]/name"
, xml,
XPathConstants.NODESET);
System.out.println(
"\nStudents with branch IT:"
);
printNodes(nodes);
nodes = (NodeList)xpath.evaluate(
"/students/student[age <= 20]/name"
, xml,
XPathConstants.NODESET);
System.out.println(
"\nStudents of age less than equal to 20:"
);
printNodes(nodes);
nodes = (NodeList)xpath.evaluate(
"/students/student[position() < 5]/name"
, xml,
XPathConstants.NODESET);
System.out.println(
"\nFirst Four Students: "
);
printNodes(nodes);
}
public
static
void
printNodes(NodeList nodes)
{
for
(
int
i =
0
; i < nodes.getLength(); i++) {
System.out.println(
(i +
1
) +
". "
+ nodes.item(i).getTextContent());
}
}
}