如何在java中更新xml文件

2022-09-03 18:35:04

我有一个xml文件调用数据.xml如下代码所示。该项目可以从客户端运行没有问题,并且可以读取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

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

    }

答案 1

首先加载 XML 文件...

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

现在,有几种方法可以做到这一点,但很简单,您可以使用xpath API来查找所需的节点并更新其内容。

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

然后将文件保存回文件...Document

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

答案 2

首先,您的XML中有一个错误,您有额外的标记。我已经删除了它。现在,您有两个选项可以使用 或 .我建议的原因是,您可以使用完整的XML来阅读,对于像这样的一小部分XML,这是更好的选择。<data>SAXDOMDOMDOM

法典

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

更正的 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>

推荐