How to use xpath to read nodes from xml file
Tech-Today

How to use xpath to read nodes from xml file


XPath is a java library that let us read a complicated xml document with ease.

In our simple example below we have an xml that contains computers with some random tags like os.

<computers>
<windows>
<lenovo model="g50">
<year>2015</year>
</lenovo>
<lenovo model="g5040">
<year>2014</year>
</lenovo>
<asus>
<year>2015</year>
</asus>
<dell>
<year>2014</year>
</dell>
</windows>
<osx>
<macbookpro>
<year>2014</year>
</macbookpro>
</osx>
</computers>

For example if we want to get the lenovo node with year 2014, we then need to use the xpath feature with a parameter=/computers/windows/lenovo[year/text()='2014'].

package com.broodcamp.xstream_demo;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
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;

/**
* @author Edward P. Legaspi
**/
public class XPathDemo {

public static void main(String[] args) {
try {
new XPathDemo();
} catch (XPathExpressionException | ParserConfigurationException | SAXException | IOException
| TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public XPathDemo() throws ParserConfigurationException, SAXException, IOException, XPathExpressionException,
TransformerException {
ClassLoader classLoader = getClass().getClassLoader();
File fXmlFile = new File(classLoader.getResource("xpath_demo.xml").getFile());

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);

Transformer trans = TransformerFactory.newInstance().newTransformer();
StringWriter writer = new StringWriter();
trans.transform(new DOMSource(doc), new StreamResult(writer));
System.out.println(writer.getBuffer().toString().replaceAll("\n|\r", ""));

XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xPath.compile("/computers/windows/lenovo[year/text()='2014']");
Object result = expr.evaluate(doc, XPathConstants.NODE);

NodeList nodes = (NodeList) result;

for (int i = 0; i < nodes.getLength(); i++) {
System.out.println("nodes: " + nodes.item(i).getTextContent());
}
}

}




- Do Some Initialization Work After The Web Application Initialization Process
We can achieve this by using a webListener. See code below: package com.czetsuya; import java.text.MessageFormat; import java.util.ResourceBundle; import javax.inject.Inject; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener;...

- How To Send An Email In Glassfish Using Javamail Session Injection
This tutorial will teach us how to send an email in Glassfish using JavaMail session injection. It use gmail for sending the email. Steps: 1.) First we need to create a JavaMail session by, opening Glassfish admin: http://localhost:4848, and navigating...

- How To Receive An Asynchronous Jms Message
This tutorial assumes that you have glassfish installed and followed the 2 previous tutorials: http://czetsuya-tech.blogspot.com/2012/06/how-to-setup-set-jms-factory-and-queue.html http://czetsuya-tech.blogspot.com/2012/06/how-to-send-jms-message-to-jms-queue.html...

- Create A Primary Key Column With Sequence Generated Value In Hibernate
For example you have a class User: package org.kalidad.seamexercises.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.SequenceGenerator; ...

- Android's Datepickerdialog And Timepickerdialog Implementation
Layout (calendar.xml) Java Class: package org.ipiel.demo.layout; import java.text.DateFormat; import java.util.Calendar; import android.app.Activity; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.os.Bundle;...



Tech-Today








.