XPath Evaluator in Java
As we know XML document is used to store and transport data. So, to access data from XML, we need something which could access each node and respective attributes data. Then the solution is XPath. XPath can be used to traverse through XML documents, to select nodes/elements, and attribute data. It is a W3C Recommendation and a flexible way of accessing different parts of an XML document. To write XPath is similar to writing path expression in your computer system to traverse to a specific location like (C:/School/Homework/assignment.docx).
Consider the Following XML Document
XPath symbols that are used to access different parts of an XML document: Symbol Description Example Result
name Selects all tags from XML having name ‘name’ /students/student/name Displays all names / This represents the root of the document /students/student/city Display each student’s city // Selects node irrespective of where it is. //age Selects and display all ages @ To access attribute value of XML tags /students/student/@branch Display each student’s branch [ ] It is used to select specific nodes /students/student/name Displays Aniket Chauhan
Let’s Practice XPath
Consider above mentioned XML document:
Select 2nd student
Select all the students with branch IT
/students/student[@branch = /”IT/”]/name
Select all the students whose age is less than equal to 20
/students/student[age <= 20]/name
First 4 students
/students/student[position() <= 4]/name
Java Code to Evaluate XPath Expression
Explanation of classes and methods used in the above code:
- The javax.xml.Parsers.DocumentBuilder class defines the API to obtain DOM instances from an XML document.
- parse() method parse the content of the given file as an XML document and return a new DOM object.
- normalize() method normalize the content of the given file as an XML document.
- The javax.xml.xpath.XPathFactory class instance can be used to create XPath objects which contain evaluate() method to evaluate our written xpath and return string/Node/NodeSet, anyone, according to the passed parameter (see evaluate() method inside code).
- position() is an XPath function that returns the position of the currently specified tag. (In the above code specified tag is ‘student’). Similarly, XPath provides a list of useful functions, you can explore it.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.