简体   繁体   English

如何在java中更新xml文件

[英]How to update xml files in java

I have a xml file call data.xml like the code below.我有一个 xml 文件调用 data.xml 像下面的代码。 The project can run from client side no problem and it can read the xml file.该项目可以从客户端运行没问题,它可以读取 xml 文件。 The problem I have now is II 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我的 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...首先加载 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 Document back 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);

Firstly there is an error in your XML you have extra <data> tag .首先,您的 XML 中有错误,您有额外的<data>标签。 I have removed it.我已经删除了。 Now you have two options you could either use SAX or DOM .现在您有两个选项可以使用SAXDOM 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.我建议使用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>

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!希望能帮助到你!

Underscore-java library can read xml to the linked hash map and regenerate xml after modification. Underscore-java库可以将 xml 读取到链接的哈希映射中,并在修改后重新生成 xml。 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 = U.fromXmlMap(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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM