How to update xml files in java

后端 未结 4 1840
悲&欢浪女
悲&欢浪女 2020-12-17 18:00

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 writ

4条回答
  •  感动是毒
    2020-12-17 18:25

    Start by loading the XML file...

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

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

提交回复
热议问题