如何在java

时间:2015-07-29 07:14:46

标签: java xml

我有一个xml文件调用data.xml,如下面的代码。项目可以从客户端运行没问题,它可以读取xml文件。我现在遇到的问题是我想编写一个可以更新startdate和enddate的函数。我不知道如何开始。将不胜感激。

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

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

    }

4 个答案:

答案 0 :(得分:8)

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

代码

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>

答案 1 :(得分:6)

首先加载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 :(得分:1)

这是我尝试更新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");

以下是我使用过的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 -->

希望它有所帮助!

答案 3 :(得分:0)

Underscore-java库可以将xml读取到链接的哈希映射,并在修改后重新生成xml。我是该项目的维护者。 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 = (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>