How to update node value in xml java -


i working on xml project. far, have link xml java class using dom parser. have code provide below. struggling updating startdate's month 1 2/1/2013, 3/1/2013... change in xml file accordingly. have method call updatedate @ bottom, xml file won't update it's value when call it. appreciated

data.xml before

  <?xml version="1.0" encoding="utf-8"> <data>        <username>hello123</username>        <startdate>01/01/2011</startdate>        <enddate>06/01/2013</enddate>     </data> 

desire data.xml after

 <?xml version="1.0" encoding="utf-8">     <data>            <username>hello123</username>            <startdate>02/01/2011</startdate> <--- change             <enddate>06/01/2013</enddate>         </data> 

main.java

     public class main {              public static void main(string[] args) {                 calendar cal2 = null;                    string username = null;                  string startdate = null;                  string enddate = null;                  string date = null;                  string date_end = null;                  try {                    file data = new file("data.xml");                 documentbuilderfactory dbfactory = documentbuilderfactory.newinstance();                 documentbuilder dbuilder = dbfactory.newdocumentbuilder();                 document doc = dbuilder.parse(data);                 doc.getdocumentelement().normalize();                    (int = 0; < 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                  //end date                   date date_end = new simpledateformat("mm/dd/yyyy", locale.english).parse(enddate);               calendar end_date_cal = calendar.getinstance();                 end_date_cal.settime(date_end);                   // initial date          date date_int = new simpledateformat("mm/dd/yyyy", locale.english).parse(date);               cal2 = calendar.getinstance();                 cal2.settime(date_int);                //call method      updatedate(cal2);                      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);                      system.out.println("update successfully");             }      }     catch (exception ex) {               log.error(ex.getmessage());                  ex.printstacktrace();                }          }        private static void updatedate(calendar cal2){           cal2.add(calendar.month, 1);           //need push calendar         }         private static string getvalue(string tag, element element) {               nodelist nodes = element.getelementsbytagname(tag).item(0).getchildnodes();                node node = (node) nodes.item(0);                return node.getnodevalue();              }    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);         } 

java 8's time api

datetimeformatter formatter = datetimeformatter.ofpattern("m/d/yyyy"); localdate ld = localdate.parse("2/1/2013", formatter); system.out.println("from " + formatter.format(ld)); ld = ld.plusmonths(1); system.out.println("to " + formatter.format(ld)); 

which prints

from 2/1/2013 3/1/2013 

but, never apply value xml document. tried demonstrate in previous question, need change textcontent of node...

node.settextcontent(formatter.format(ld)) 

which why suggested using xpath instead of walking document content

for example...

import java.io.file; import java.io.ioexception; import java.time.localdate; import java.time.format.datetimeformatter; import java.time.format.datetimeparseexception; import javax.xml.parsers.documentbuilder; import javax.xml.parsers.documentbuilderfactory; import javax.xml.parsers.parserconfigurationexception; import javax.xml.transform.outputkeys; import javax.xml.transform.transformer; import javax.xml.transform.transformerexception; import javax.xml.transform.transformerfactory; import javax.xml.transform.transformerfactoryconfigurationerror; 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.xpathexpressionexception; import javax.xml.xpath.xpathfactory; import org.w3c.dom.domexception; import org.w3c.dom.document; import org.w3c.dom.node; import org.xml.sax.saxexception;  public class updatexml {      public static void main(string[] args) {          try {             documentbuilderfactory f = documentbuilderfactory.newinstance();             documentbuilder b = f.newdocumentbuilder();             document doc = b.parse(new file("data.xml"));              xpath xpath = xpathfactory.newinstance().newxpath();             node startdatenode = (node) xpath.compile("/data/startdate").evaluate(doc, xpathconstants.node);             startdatenode.settextcontent(addmonthto(startdatenode.gettextcontent()));              xpath = xpathfactory.newinstance().newxpath();             node enddatenode = (node) xpath.compile("/data/enddate").evaluate(doc, xpathconstants.node);             enddatenode.settextcontent(addmonthto(enddatenode.gettextcontent()));              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("adata.xml"));             tf.transform(domsource, sr);         } catch (parserconfigurationexception | saxexception | ioexception | xpathexpressionexception | domexception | transformerfactoryconfigurationerror | illegalargumentexception | transformerexception exp) {             exp.printstacktrace();         }     }      public static string addmonthto(string value) {          string patterns[] = {"m/d/yyyy", "m/dd/yyyy", "mm/d/yyyy", "mm/dd/yyyy"};          localdate ld = null;         (string pattern : patterns) {             try {                 ld = localdate.parse(value, datetimeformatter.ofpattern(pattern));                 break;             } catch (datetimeparseexception exp) {             }         }          if (ld == null) {             throw new datetimeparseexception("could not parse " + value + " available patterns", value, -1);         }          ld = ld.plusmonths(1);         return datetimeformatter.ofpattern("mm/dd/yyyy").format(ld);      }  } 

which took...

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

and outputted...

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

i want startdate 6 months earlier enddate

java 8

string enddatevalue = "07/01/2013";  datetimeformatter formatter = datetimeformatter.ofpattern("mm/dd/yyyy"); localdate enddate = localdate.parse(enddatevalue, formatter); localdate startdate = enddate.minusmonths(6);  string startdatevalue = formatter.format(startdate); 

calendar

i'd prefer joda-time, but

string enddatevalue = "07/01/2013"; simpledateformat sdf = new simpledateformat("mm/dd/yyyy"); date enddate = sdf.parse(enddatevalue);  calendar cal = calendar.getinstance(); cal.settime(enddate); cal.add(calendar.month, -6);  date startdate = cal.gettime(); string startdatevaue = sdf.format(startdate); 

Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -