[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.

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")
                                                .item(0).getTextContent();
    Double price = Double.parseDouble(product
                  .getElementsByTagName("price").item(0).getTextContent());

    Product prod = new Product();
    prod.setName(name);
    prod.setPrice(price);
    products.add(prod);
}
System.out.println(products);

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s