Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I append a node to an existing XML file in java

Tags:

public static void addALLToXML(Collection<Server> svr) throws IOException,       ParserConfigurationException, TransformerException {     DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory         .newInstance();     DocumentBuilder documentBuilder = documentBuilderFactory         .newDocumentBuilder();     Document document = documentBuilder.newDocument();      // Root Element     Element rootElement = document.createElement("Servers");     document.appendChild(rootElement);      for (Server i : svr)     {         // server elements         Element server = document.createElement("server");         rootElement.appendChild(server);          Element name = document.createElement("name");         name.appendChild(document.createTextNode(i.getName()));         server.appendChild(name);          Element port = document.createElement("port");         port.appendChild(document.createTextNode(Integer.toString(i.getPort())));         server.appendChild(port);     }      TransformerFactory transformerFactory = TransformerFactory.newInstance();     Transformer transformer = transformerFactory.newTransformer();     DOMSource source = new DOMSource(document);      StreamResult result = new StreamResult("/home/user/server.xml");     transformer.transform(source, result); } 

This is the function I need help with:

public static void addNodeToXML(String nameIn, String portIn)       throws ParserConfigurationException, SAXException, IOException {     DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory             .newInstance();     DocumentBuilder documentBuilder = documentBuilderFactory             .newDocumentBuilder();      /* parse existing file to DOM */     Document document = documentBuilder             .parse(new File("/home/user/server.xml"));      // Root Element     Element rootElement = document.createElement("Servers");     document.appendChild(rootElement);      // server elements     Element server = document.createElement("server");     rootElement.appendChild(server);      Element name = document.createElement("name");     name.appendChild(document.createTextNode(nameIn));     server.appendChild(name);      Element port = document.createElement("port");     port.appendChild(document.createTextNode(portIn));     server.appendChild(port); } 

Original:

<Servers>  <server>   <name>something</name>   <port>port</port>  </server>  </Servers> 

Wanted:

<Servers>    <server>    <name>something</name>    <port>port</port>   </server>   <server>    <name>something</name>    <port>port</port>   </server> <Servers> 
like image 664
stackoverflow Avatar asked Jun 22 '11 20:06

stackoverflow


People also ask

How add node to XML file in Java?

Get the Document Element using getDocumentElement() API method of Document. Create a new Element, using createElement(String tagName ) API method of Document. Append the new node at the end of list of children of the Document Element, with appendChild(Node newChild) API method of Node.

How do you add an attribute to an existing XML file in Java?

in DOM parser it is very easy. get your node and simply use this function. ((Element)node). setAttribute("attr_name","attr_value");

Which line of code adds a new node into an XML file?

Add a Node - appendChild()


1 Answers

The following complete example will read an existing server.xml file from the current directory, append a new Server and re-write the file to server.xml. It does not work without an existing .xml file, so you will need to modify the code to handle that case.

import java.util.*; import javax.xml.transform.*; import javax.xml.transform.stream.*; import javax.xml.transform.dom.*; import org.w3c.dom.*; import javax.xml.parsers.*;  public class AddXmlNode {     public static void main(String[] args) throws Exception {          DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();         DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();         Document document = documentBuilder.parse("server.xml");         Element root = document.getDocumentElement();          Collection<Server> servers = new ArrayList<Server>();         servers.add(new Server());          for (Server server : servers) {             // server elements             Element newServer = document.createElement("server");              Element name = document.createElement("name");             name.appendChild(document.createTextNode(server.getName()));             newServer.appendChild(name);              Element port = document.createElement("port");             port.appendChild(document.createTextNode(Integer.toString(server.getPort())));             newServer.appendChild(port);              root.appendChild(newServer);         }          DOMSource source = new DOMSource(document);          TransformerFactory transformerFactory = TransformerFactory.newInstance();         Transformer transformer = transformerFactory.newTransformer();         StreamResult result = new StreamResult("server.xml");         transformer.transform(source, result);     }      public static class Server {         public String getName() { return "foo"; }         public Integer getPort() { return 12345; }     } } 

Example server.xml file:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Servers>   <server>     <name>something</name>     <port>port</port>   </server> </Servers> 

The main change to your code is not creating a new "root" element. The above example just uses the current root node from the existing server.xml and then just appends a new Server element and re-writes the file.

like image 141
andyb Avatar answered Sep 21 '22 02:09

andyb