How to read an XML file using XPath in Java

0 votes
Is there any simple way to read an XML file using XPath in Java?
Jun 14, 2018 in Java by Annie
• 240 points
3,973 views

1 answer to this question.

0 votes

Import the packages required to work with XPath:

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

Then create instances of DocumentBuilderFactory, DocumentBuilder and document:

public class XPathReaderDemo {


public static void main(String[] args) {


try {

         File inputFile = new File("D:\\students.txt");

         DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

         DocumentBuilder dBuilder;


         dBuilder = dbFactory.newDocumentBuilder();


         Document doc = dBuilder.parse(inputFile);

         doc.getDocumentElement().normalize();


         XPath xPath =  XPathFactory.newInstance().newXPath();


         String expression = "/class/student";       

         NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(

            doc, XPathConstants.NODESET);

for (int i = 0; i < nodeList.getLength(); i++) {

            Node nNode = nodeList.item(i);

            System.out.println("\nCurrent Element :" + nNode.getNodeName());

           

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

               Element eElement = (Element) nNode;

              

               System.out.println("First Name : "

                  + eElement

                  .getElementsByTagName("firstname")

                  .item(0)

                  .getTextContent());

               System.out.println("Last Name : "

                  + eElement

                  .getElementsByTagName("lastname")

                  .item(0)

                  .getTextContent());

               System.out.println("email : "

                  + eElement

                  .getElementsByTagName("email")

                  .item(0)

                  .getTextContent());

               System.out.println("Marks : "

                  + eElement

                  .getElementsByTagName("marks")

                  .item(0)

                  .getTextContent());

            }

         }

 } catch (ParserConfigurationException e) {

         e.printStackTrace();

      } catch (SAXException e) {

         e.printStackTrace();

      } catch (IOException e) {

         e.printStackTrace();

      } catch (XPathExpressionException e) {

         e.printStackTrace();

      }


  }


}
answered Jun 14, 2018 by Akrati
• 3,190 points

Related Questions In Java

0 votes
1 answer

how to read csv file form sftp connection and store into string object in java code and convert into json.....post it using rest api

Hey, @Pooja, Before starting with anything you should ...READ MORE

answered May 13, 2020 in Java by Roshni
• 10,520 points
3,507 views
0 votes
3 answers

How to read a Text File in Java?

You can use readAllLines and the join method to ...READ MORE

answered Jul 28, 2018 in Java by samarth295
• 2,220 points
2,138 views
0 votes
1 answer

How to append text to an existing file in Java?

Java 7+ If you just need to do ...READ MORE

answered Dec 30, 2020 in Java by Gitika
• 65,910 points

edited Jul 6, 2023 by Khan Sarfaraz 970 views
+5 votes
4 answers

How to execute a python file with few arguments in java?

You can use Java Runtime.exec() to run python script, ...READ MORE

answered Mar 27, 2018 in Java by DragonLord999
• 8,450 points

edited Nov 7, 2018 by Omkar 79,591 views
0 votes
1 answer

How to pretty print XML from Java?

Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); //initialize StreamResult ...READ MORE

answered Jul 4, 2018 in Java by Akrati
• 3,190 points
1,684 views
0 votes
1 answer

org.xml.sax.SAXParseException: How to handle this exception?

This is often caused by a white ...READ MORE

answered Jul 9, 2018 in Java by sharth
• 3,370 points
5,724 views
0 votes
1 answer

Hosting spring boot app

There are a couple of things wrong ...READ MORE

answered Sep 11, 2018 in AWS by Priyaj
• 58,090 points
2,133 views
0 votes
1 answer

web.xml file is missing in my eclipse IDE

Very simple. You will find Deployment Descriptor ...READ MORE

answered Nov 27, 2018 in Java by Omkar
• 69,210 points
3,631 views
0 votes
2 answers

How to read a text file in Java?

You can use Scanner class to read ...READ MORE

answered Aug 9, 2018 in Java by Parth
• 4,630 points
781 views
0 votes
2 answers

How to convert an int array to string using tostring method in java?

Use java.util.Arrays: String res = Arrays.toString(array); System. ...READ MORE

answered Aug 16, 2019 in Java by Sirajul
• 59,230 points
2,144 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP