How do I append a node to an existing XML file in java
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.
Append nodes into existing XML File with java
Without a library you can do something like this:
Element dataTag = doc.getDocumentElement();
Element peopleTag = (Element) dataTag.getElementsByTagName("people").item(0);
Element newPerson = doc.createElement("person");
Element firstName = doc.createElement("firstName");
firstName.setTextContent("Tom");
Element lastName = doc.createElement("lastName");
lastName.setTextContent("Hanks");
newPerson.appendChild(firstName);
newPerson.appendChild(lastName);
peopleTag.appendChild(newPerson);
Which results:
...
<person>
<firstName>Thomas</firstName>
<lastName>Tester</lastName>
<access>false</access>
<images>
<img>tt001.jpg</img>
</images>
</person>
<person>
<firstName>Tom</firstName>
<lastName>Hanks</lastName>
</person>
</people>
</data>
how to append node from xml document to existing xml document
- Get Node to add from first Document;
- Adopt Node (see Document.adopt(Node)) from first Document to the second Document;
- Appent adopted Node as a child to second Document structure (see Node.appendChild(Node).
Update.
Code:
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
Document tournament = builder.parse(new File("b.xml"));
Document tournaments = builder.parse(new File("a.xml"));
Node tournamentElement = tournament.getFirstChild();
Node ndetournament = tournaments.getDocumentElement();
Node firstDocImportedNode = tournaments.adoptNode(tournamentElement);
ndetournament.appendChild(firstDocImportedNode);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(new DOMSource(tournaments), new StreamResult(System.out));
Result:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<tournaments>
<tournament>
<name>a</name>
</tournament>
<tournament>
<name>b</name>
</tournament>
<tournament>
<name>c</name>
</tournament>
<tournament>
<name>d</name>
</tournament>
</tournaments>
How to append an existing XML file using DOM without overwriting the existing data? in java
It's pretty easy. Say, you want to append new Employees
to your XML. Instead of creating a new root you'd simply find it using getElementsByName()
like
// find root
NodeList rootList = doc.getElementsByName("Employees");
Node root = rootList.item(0);
Element employee = doc.createElement("employee"); //create new Element
root.appendChild(employee); // append as before
There's a Document.getElementById()
method as well that you could use if an element has been assigned an identifier. To insert something deep down the tree use XPath
to find the node first then append()
as usual.
EDIT : (Sample code added)
You can't have two root nodes i.e. two <Employees>
tags as root. That's invalid XML. What you need is multiple <Employee>
tags inside one single root <Employees>
tag. Also, stick to either camel or capital case. I'm using capitals for consistency.
// find root
NodeList rootList = doc.getElementsByName("Employees");
Node root = rootList.item(0);
// append using a helper method
root.appendChild(createEmployee(doc, "male", "John", "Doe"));
public Element createEmployee(Document doc,
String gender, String fname, String lname) {
// create new Employee
Element employee = doc.createElement("Employee");
employee.setAttribute("gender", gender);
// create child nodes
Element firstName = doc.createElement("FirstName");
firstName.appendChild(doc.createTextNode(fname));
Element lastName = doc.createElement("LastName");
lastName.appendChild(doc.createTextNode(lname));
// append and return
employee.appendChild(firstName);
employee.appendChild(lastName);
return employee;
}
Append node to an existing xml-Java
XPath will help you to find nodes, but not really append them. I don't think you'd find it particularly useful here.
Which XML API are you using? If it's the W3C DOM (urgh) then you'd do something like:
Element newB = document.createElement("B");
Element newC = document.createElement("c");
newC.setTextContent("11");
Element newD = document.createElement("d");
newD.setTextContent("21");
Element newE = document.createElement("e");
newE.setTextContent("31");
newB.appendChild(newC);
newB.appendChild(newD);
newB.appendChild(newE);
document.getDocumentElement().appendChild(newB);
Related Topics
How to Determine the Primitive Type of a Primitive Variable
Why Does My Aes Encryption Throws an Invalidkeyexception
Reverse Hashmap Keys and Values in Java
Apache Httpclient 4.0.3 - How to Set Cookie with Sessionid for Post Request
Why Is Files.Lines (And Similar Streams) Not Automatically Closed
How to Change the Name of a Java Application Process
Whats the Use of Saying <? Extends Someobject> Instead of <Someobject>
Import Com.Sun.Image.Codec.Jpeg.*
Spark Spark-Submit --Jars Arguments Wants Comma List, How to Declare a Directory of Jars
Java:Read Last N Lines of a Huge File
Rejectedexecutionexception Inside Single Executor Service
How to Set an Environment Variable at Runtime from Java
Is Executorservice (Specifically Threadpoolexecutor) Thread Safe
How to Unzip Files Recursively in Java
Java: Local Variable Mi Defined in an Enclosing Scope Must Be Final or Effectively Final
Include External Jar When Running Java -Jar
Java: Why am I Required to Initialize a Primitive Local Variable