StackStalk
  • Home
  • Java
    • Java Collection
    • Spring Boot Collection
  • Python
    • Python Collection
  • C++
    • C++ Collection
    • Progamming Problems
    • Algorithms
    • Data Structures
    • Design Patterns
  • General
    • Tips and Tricks

Saturday, February 1, 2014

Parse XML file using XPath in Java

 February 01, 2014     Java     No comments   

In this article, we will explore XPath and understand how to parse XML file using XPath in Java.

XPath Introduction

XPath is a language for defining parts of an XML document. XPath gets its name from its use of a path notation as in URLs for navigating through the hierarchical structure of an XML document.

The primary syntactic construct in XPath is the expression. An XPath expression is evaluated to yield an object which has one of the following four basic types.

  1. Node sets - Collection of nodes
  2. Boolean
  3. Number or
  4. String
With this introduction let us look at some XPath examples. Let us consider this basic XML document.
<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.</description>
   </book>
   <book id="bk103">
      <author>Corets, Eva</author>
      <title>Maeve Ascendant</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-11-17</publish_date>
      <description>After the collapse of a nanotechnology 
      society in England, the young survivors lay the 
      foundation for a new society.</description>
   </book>
</catalog>

XPath Examples

Example
XPath Expression
Output
Get title of book with id as “bk02” /catalog/book[@id='bk102']/title Midnight Rain
Get title of all books /catalog/book/title XML Developer's Guide Midnight Rain Maeve Ascendant
Get title of all books with genre as “Fantasy” /catalog/book[genre = 'Fantasy']/title Midnight Rain Maeve Ascendant

Java program to parse XML file using XPath expressions

To understand this program we need basics of DOM parser implementation. Refer DOM Parser to read XML file. Java supports XPath package which is pretty straightforward to use once we understand XPath expressions.

Implementation to evaluate XPath expressions

package com.sourcetricks.xpath;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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.xml.sax.SAXException;

public class XPathTest {

 public static void main(String[] args) {
  
  try {
   // Setup the parser
   DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
   DocumentBuilder builder = builderFactory.newDocumentBuilder();
   
   // Read the XML file
   File inputFile = new File("resources/input.xml");
   InputStream inputStream = new FileInputStream(inputFile);
   
   // Parse the XML file   
   Document doc = builder.parse(inputStream);
   
   // Create an XPath instance
   XPath xPath = XPathFactory.newInstance().newXPath();
      
   // Evaluate simple expressions
   String expression1 = "/catalog/book[@id='bk102']/title";
   String author = xPath.evaluate(expression1, doc);
   System.out.println("<<< Using XPath to read node values >>>");
   System.out.println(author);
   
   // Evaluate XPath expression and get multiple values
   String expression2 = "/catalog/book/title";
   System.out.println("<<< Using XPath to read set of node values >>>");
   NodeList titleList = (NodeList) xPath.compile(expression2).evaluate(doc, XPathConstants.NODESET);
   for ( int i = 0; i < titleList.getLength(); i++ ) {
    System.out.println(titleList.item(i).getTextContent());
   }
   
   // Evaluate XPath expression based on another nodes value
   String expression3 = "/catalog/book[genre = 'Fantasy']/title";
   System.out.println("<<< Using XPath to read set of node values with specific values >>>");
   titleList = (NodeList) xPath.compile(expression3).evaluate(doc, XPathConstants.NODESET);
   for ( int i = 0; i < titleList.getLength(); i++ ) {
    System.out.println(titleList.item(i).getTextContent());
   }
  }
  catch ( FileNotFoundException e ) {
   e.printStackTrace();
  } catch (XPathExpressionException e) {
   e.printStackTrace();
  } catch (SAXException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (ParserConfigurationException e) {
   e.printStackTrace();
  }
 }
}
Output:-
<<< Using XPath to read node values >>>
Midnight Rain
<<< Using XPath to read set of node values >>>
XML Developer's Guide
Midnight Rain
Maeve Ascendant
<<< Using XPath to read set of node values with specific values >>>
Midnight Rain
Maeve Ascendant
  • Share This:  
Newer Post Older Post Home

0 comments:

Post a Comment

Follow @StackStalk
Get new posts by email:
Powered by follow.it

Popular Posts

  • Avro Producer and Consumer with Python using Confluent Kafka
    In this article, we will understand Avro a popular data serialization format in streaming data applications and develop a simple Avro Produc...
  • Monitor Spring Boot App with Micrometer and Prometheus
    Modern distributed applications typically have multiple microservices working together. Ability to monitor and manage aspects like health, m...
  • Server-Sent Events with Spring WebFlux
    In this article we will review the concepts of server-sent events and work on an example using WebFlux. Before getting into this article it ...
  • Implement caching in a Spring Boot microservice using Redis
    In this article we will explore how to use Redis as a data cache for a Spring Boot microservice using PostgreSQL as the database. Idea is to...
  • Python FastAPI microservice with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Spring Boot with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Getting started with Kafka in Python
    This article will provide an overview of Kafka and how to get started with Kafka in Python with a simple example. What is Kafka? ...
  • Getting started in GraphQL with Spring Boot
    In this article we will explore basic concepts on GraphQL and look at how to develop a microservice in Spring Boot with GraphQL support. ...

Copyright © StackStalk