Thursday, 26 May 2016

How to read XML node's attributes of a configuration file using java

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLReading {
   
    public static void main(String args[]) {

        try {

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse("E:\\Aneesh\\xmlfolder\\xmlfile.config");
            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xPath = xPathfactory.newXPath();
            XPathExpression expr = xPath.compile("//configuration/appSettings/add[@key]");
            NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            for (int c = 0; c < nodeList.getLength(); c++) {
                Node currentItem = nodeList.item(c);
                String key = currentItem.getAttributes().getNamedItem("key").getNodeValue();
                String value = currentItem.getAttributes().getNamedItem("value").getNodeValue();
                System.out.println("Key:"+key+" Value:"+value);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}


Sample XML file

xmlfile.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="Aneesh" value="aneesh.aneesh83@gmail.com"/>
    <add key="Akshay" value="vishnu.akshayprabhu@gmail.com"/>
    </appSettings>
</configuration>

No comments:

Post a Comment