[Java] – How to use XPath to parse XML files?

What is it ?

The xPath allows us to select only a part of our document using a very similar syntax to the folder structure of our operating system. To facilitate the pursuit of our document data.

Why use it ?

With the help of xPath we do not need to add many ifs in the code that reads our xml file which greatly facilitates the process of filtering data from an XML file to generate various reports for example.


List<Product> products = new ArrayList<Produto>();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("src/sale.xml");

XPath xPath = XPathFactory.newInstance().newXPath();
String ex = "/sale/products/product[2]";
XPathExpression xPathExpression = xPath.compile(expression);
NodeList result = (NodeList) 
xPathExpression.evaluate(document, XPathConstants.NODESET);

for(int i = 0; i < result.getLength();i++) {
    Element product = (Element) result.item(i);
    String name = product.getElementsByTagName("name")
    Double price = Double.parseDouble(product

    Product prod = new Product();

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s