Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update xml files in java

Tags:

java

xml

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);

    }
like image 568
Big Ticket Avatar asked Jul 29 '15 07:07

Big Ticket


People also ask

How do I update an XML file?

To update data in an XML column, use the SQL UPDATE statement. Include a WHERE clause when you want to update specific rows. The entire column value will be replaced. The input to the XML column must be a well-formed XML document.

How do you add data to XML file in Java?

Element root = dct. getDocumentElement(); root. appendChild(child1);

Can we use XML in Java?

JAVA provides excellent support and a rich set of libraries to parse, modify or inquire XML documents. This tutorial will teach you basic XML concepts and the usage of various types of Java based XML parsers in a simple and intuitive way.


1 Answers

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);
like image 172
MadProgrammer Avatar answered Oct 08 '22 13:10

MadProgrammer