Thursday, 26 May 2016

How to update an XML tag's attribute using java


XML file before update:-

xmlfile.config

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


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
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.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

class UpdateXMLAttribute {
    public static  void main(String args[]){
      
        try{
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.parse("E:\\Aneesh\\xmlfolder\\xmlfile.config"); //xml file path  
            StreamResult result = new StreamResult("E:\\Aneesh\\xmlfolder\\xmlfile.config");    
                
            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            XPathExpression expr = xpath.compile("//configuration/appSettings/add[@key]");//specifying the nodes
            NodeList nodelist = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
         
              for (int c = 0; c < nodelist.getLength(); c++)
                {
                Node currentItem = nodelist.item(c);
                  
                String key = currentItem.getAttributes().getNamedItem("key").getNodeValue();
               if(key.equals("Akshay")){
                 
                   currentItem.getAttributes().getNamedItem("value").setTextContent("Aneesh");//updating the attribute
               
                  }
               Transformer transformer = TransformerFactory.newInstance().newTransformer();
               transformer.setOutputProperty(OutputKeys.INDENT, "yes");
               DOMSource source = new DOMSource(document);
               transformer.transform(source, result);
                }
          
          }
          catch(Exception e){
              e.printStackTrace();
              
          }
    }

    }

XML file after update:-

xmlfile.config

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

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>