How to update xml files in java

java modify xml file with xpath
how to update attribute value in xml using java
best way to modify xml in java
how to search and replace a tag value in xml file using java
modify xml string in java
modify xml file in java using sax parser example
how to set node value in xml using java
how to append data in xml file using java

I have a xml file call data.xml like the code below. The project can run from client side no problem and it can read the xml file. The problem I have now is I I want to write a function that can update the startdate and enddate. I have no idea how to get start. Help will be appreciated.

  <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<data>
       <username>admin</username>
       <password>12345</password>
       <interval>1</interval>
       <timeout>90</timeout>
       <startdate>01/01/2013</startdate>
       <enddate>06/01/2013</enddate>
       <ttime>1110</ttime>
    </data>

my main.java

    public class main
    {
     public static void main(String[] args) 
      {
          Calendar cal2 =null;

    try {   

              //read the xml      
              File data = new File("data.xml");  
              DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();         
              DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();           
              Document doc = dBuilder.parse(data);         
              doc.getDocumentElement().normalize();

     for (int i = 0; i < nodes.getLength(); i++) {     
              Node node = nodes.item(i);           
                if (node.getNodeType() == Node.ELEMENT_NODE) {     
                    Element element = (Element) node;   
                    username = getValue("username", element);
                    startdate = getValue("startdate", element);
                    enddate = getValue("enddate", element);
                  }
       }


  date = startdate; 
  Date date_int = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse(date); 
  cal2 = Calendar.getInstance(); 
 cal2.setTime(date_int); 


     //loop the child node to update the initial date
              for (int i = 0; i < nodes.getLength(); i++) {    
                  Node node = nodes.item(i);           
                    if (node.getNodeType() == Node.ELEMENT_NODE) {     
                        Element element = (Element) node;

                        setValue("startdate", element , date_int.toString());
                  }
              }

            //write the content in xml file
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                DOMSource source = new DOMSource(doc);
                StreamResult result = new StreamResult(new File("data.xml"));
                transformer.transform(source, result);

        } catch (Exception ex) {    
          log.error(ex.getMessage());       
          ex.printStackTrace();       
        }
    }


      private static void setValue(String tag, Element element , String input) {  
            NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();   
            Node node = (Node) nodes.item(0); 
            node.setTextContent(input);

    }

Start by loading the XML file...

DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
DocumentBuilder b = f.newDocumentBuilder();
Document doc = b.parse(new File("Data.xml"));

Now, there are a few ways to do this, but simply, you can use the xpath API to find the nodes you want and update their content

XPath xPath = XPathFactory.newInstance().newXPath();
Node startDateNode = (Node) xPath.compile("/data/startdate").evaluate(doc, XPathConstants.NODE);
startDateNode.setTextContent("29/07/2015");

xPath = XPathFactory.newInstance().newXPath();
Node endDateNode = (Node) xPath.compile("/data/enddate").evaluate(doc, XPathConstants.NODE);
endDateNode.setTextContent("29/07/2015");

Then save the Document back to the file...

Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.setOutputProperty(OutputKeys.METHOD, "xml");
tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

DOMSource domSource = new DOMSource(doc);
StreamResult sr = new StreamResult(new File("Data.xml"));
tf.transform(domSource, sr);

How to update xml files in java, Use Node. getAttributes() to get a NamedNodeMap of the element's attributes. In this example, we demonstrate the use of DOM parser to modify an existing XML file : Add a new element; Update existing element attribute ; Update existing element value; Delete existing element; 1. XML file. See before and after XML file. File : file.xml – Original XML file.

Firstly there is an error in your XML you have extra <data> tag . I have removed it. Now you have two options you could either use SAX or DOM. I would suggest DOM reason being that you can read full XML using DOM and for a small piece of XML like this it's better choice.

Code

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

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 org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

public class ModifyXMLFile {

    public static void main(String argv[]) {

        try {
            String filepath = "file.xml";
            DocumentBuilderFactory docFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(filepath);

            // Get the root element
            Node data= doc.getFirstChild();

            Node startdate = doc.getElementsByTagName("startdate").item(0);

            // I am not doing any thing with it just for showing you
            String currentStartdate = startdate.getNodeValue();

            DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
            Date today = Calendar.getInstance().getTime();

            startdate.setTextContent(df.format(today));

            // write the content into xml file
            TransformerFactory transformerFactory = TransformerFactory
                    .newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(filepath));
            transformer.transform(source, result);

            System.out.println("Done");

        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Corrected XML

<?xml version="1.0" encoding="UTF-8"?>
<data>
   <username>admin</username>
   <password>12345</password>
   <interval>1</interval>
   <timeout>90</timeout>
   <startdate>29/07/2015</startdate>
   <enddate>06/01/2013</enddate>
   <ttime>1110</ttime>
</data>

Modify XML file in Java (DOM Parser), Use NamedNodeMap. getNamedItem to get a specific attributes by name. In this article, we will learn how to update or modify the existing XML file in Java using DOM Parser. In this example, we have a list of User elements in the XML file and we will modify these User elements in XML with Java program.

This an example which i have tried for updating the xml files.

        String filepath="Test.xml";
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder;
        docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(filepath);
        Node company = doc.getFirstChild();

        /**
         * Get the param from xml and set value
         */
        Node search = doc.getElementsByTagName("parameter").item(0);
        NamedNodeMap attr = search.getAttributes();
        Node nodeAttr = attr.getNamedItem("value");
        nodeAttr.setTextContent(param);

        /**
         * write it back to the xml
         */
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(filepath));
        transformer.transform(source, result);

        System.out.println("Done");

Following is the XML file i have used:

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
   <suite name="Testing" parallel="false">
    <parameter name="Search" value="param1"></parameter>
     <test name="TestParams" preserve-order="true">
       <classes>
         <class name="uiscreen.TestingParam"/>
       </classes>
     </test> <!-- Test -->
   </suite> <!-- Suite -->

Hope it helps!

Java DOM Parser - Modify XML Document, Start by loading the XML file DocumentBuilderFactory f = DocumentBuilderFactory.newInstance(); DocumentBuilder b = f. newDocumentBuilder(); Document� Option 1: Login as a system administrator and initiate auto update For detailed information about Java Auto Updater program, please click here . Option 2: Run Java updater (juchecker.exe) in administrator mode

Underscore-java library can read xml to the linked hash map and regenerate xml after modification. I am the maintainer of the project. Live example

import com.github.underscore.lodash.U;

public class MyClass {
    public static void main(String args[]) {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>"
        + "<data>"
        + "       <username>admin</username>"
        + "       <password>12345</password>"
        + "       <interval>1</interval>"
        + "       <timeout>90</timeout>"
        + "       <startdate>01/01/2013</startdate>"
        + "       <enddate>06/01/2013</enddate>"
        + "       <ttime>1110</ttime>"
        + "    </data>";  
        java.util.Map<String, Object> object = (java.util.Map<String, Object>) U.fromXml(xml);
        U.set(object, "data.startdate", "02/02/2013");
        U.set(object, "data.enddate", "07/02/2013");
        System.out.println(U.toXml(object)); 
    }
}

// <?xml version="1.0" encoding="UTF-8" standalone="no"?>
// <data>
//   <username>admin</username>
//   <password>12345</password>
//   <interval>1</interval>
//   <timeout>90</timeout>
//   <startdate>02/02/2013</startdate>
//   <enddate>07/02/2013</enddate>
//   <ttime>1110</ttime>
// </data>

How to modify XML file in Java - (DOM Parser), Modify XML file in java, java edit xml, how to modify xml file in java, update xml file java example, add element, delete element, update attribute value. Modify XML file in java, java edit xml, how to modify xml file in java, update xml file java example, add element, delete element, update attribute value

How to Modify or Update XML File in Java - DOM Parser, Java DOM Parser - Modify XML Document - Here is the input xml file we need to modify − In order to process it, we'll use the Java API for XML Processing (JAXP), which has been bundled with Java since version 1.4. Let's modify the customer attribute and change its value to false . First, we need to build a Document object from the XML file, and to do that, we'll use a DocumentBuilderFactory :

How to Modify or Update XML File in Java with DOM Parser, In this example, we demonstrate the use of DOM parser to modify an existing XML file : Add a new element; Update existing element attribute� On the Java Control panel Update tab, click Advanced The Automatic Update Advanced Settings dialog appears. Change the frequency and the date and time for the Java Update. Click OK. Java Update scheduler will check for newer Java updates and notify you at the scheduled frequency. For daily updates, you can select the time of the day for the update.

Modifying an XML Attribute in Java, In this article, we will learn how to update or modify existing XML file in Java using DOM Parser. Reading XML file in Java is much different from reading other files like .docx and .txt because XML file contains data between the tags. Java provides many ways to parse an XML file. There are two parsers in Java which parses an XML file: Java DOM Parser; Java SAX Parser; Java DOM Parser. The DOM API provides the classes to read and write an

Comments
  • stackoverflow.com/questions/6124239/… and stackoverflow.com/questions/7646607/…
  • At least show your code what have you tried
  • Hi MadProgrammer, thank you for your answer, I have got the xml part working. Now what if I want to update the startdate's month increase by one such as 29/07/2015, 29/8/2015, 20/10/2015 .... something like this, how should I do that? Should I create a method to do it? Can you provide an example?
  • You could simply use Java 8's Time API which has simple to use manipulation, parsing and formatting
  • Will you be able to provide an example?
  • Something similar to this
  • Hi, thank you for your respond, now I have updated my answer, how will you apply that into my code? I use Dom Parser instead of XPath. Thanks
  • Hi Shahzeb, thank you for your answer, I have got the xml part working. Now what if I want to update the startdate's month increase by one such as 29/07/2015, 29/8/2015, 20/10/2015 .... something like this, how should I do that? Should I create a method to do it? Can you provide an example?
  • My Answer already does that . please try out the code that I have given here .
  • In my answer I am only updating startdate you can add enddate
  • @gaurav not by default but you can put it in threadsafe methods