Java tutorial
//package com.java2s; import java.io.File; import java.io.IOException; 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.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; public class Main { public static String getNodeTextValue(File xmlfile, String nodeXpath) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { //logger.debug("Getting the Text value of the node"); // get the Document object. Document doc = getDocument(xmlfile); // get the Node Object for the xpath. Node node = getNodeObject(nodeXpath, doc); // Get the Attribute Value returned as a String String NodeTextValue = node.getTextContent(); //logger.debug("Node name " + nodeXpath + " and the text contains is " + NodeTextValue); //logger.debug("Returning the node text value as " + NodeTextValue); return NodeTextValue; } private static Document getDocument(File xmlfile) throws ParserConfigurationException, SAXException, IOException { //logger.debug("Creating an Object of the Document"); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(xmlfile); return doc; } private static Node getNodeObject(String xpathString, Document doc) throws XPathExpressionException { // Create a xptah object //logger.debug("Getting the node by using xpath " + xpathString); XPathFactory xpf = XPathFactory.newInstance(); XPath xpath = xpf.newXPath(); XPathExpression expr = xpath.compile(xpathString); Node node = (Node) expr.evaluate(doc, XPathConstants.NODE); //logger.debug("Returning the Node object from xml file"); return node; } }