如何在java中更新xml文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31693670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:26:21  来源:igfitidea点击:

How to update xml files in java

javaxml

提问by Big Ticket

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 文件调用 data.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>

my main.java

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

    }

采纳答案by MadProgrammer

Start by loading the XML file...

首先加载 XML 文件...

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

Then save the Documentback to the file...

然后保存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);

回答by Shahzeb

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 SAXor DOM. I would suggest DOMreason being that you can read full XML using DOMand for a small piece of XML like this it's better choice.

首先,您的 XML 中有错误,您有额外的<data>标签。我已经删除了。现在您有两个选项可以使用SAXDOM。我建议的DOM理由是,您可以使用这样DOM的一小段XML 来读取完整的 XML ,这是更好的选择。

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

<?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>

回答by Deep Mistry

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

这是我尝试更新 xml 文件的示例。

        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:

以下是我使用的 XML 文件:

<!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!

希望能帮助到你!

回答by Valentyn Kolesnikov

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

Underscore-java库可以将 xml 读取到链接的哈希映射中,并在修改后重新生成 xml。我是项目的维护者。活生生的例子

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>