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>

No comments:

Post a Comment