How to update xml files in java

后端 未结 4 1805
悲&欢浪女
悲&欢浪女 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:23

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

            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:

    
       
        
         
           
             
           
          
        
    

    Hope it helps!

提交回复
热议问题