Java HTML / XML How to - Append node from xml document to existing xml document








Question

We would like to know how to append node from xml document to existing xml document.

Answer

import java.io.StringBufferInputStream;
/*from   w  ww .java 2s .  c o m*/
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class Main {

  private static final String studentData =
    "  <students>" +
    "    <student>" +
    "        <name>a</name>" +
    "    </student>" +
    "    <student>" +
    "        <name>b</name>" +
    "    </student>" +
    "    <student>" +
    "        <name>c</name>" +
    "    </student>" +
    "</students>";


  private static final String studentB =
    "    <student>" +
    "        <name>d</name>" +
    "    </student>";

  private static DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

  public static void main(String[] args) throws Exception{
    Document currentstudents = getCurrentstudents();
    Element student =  getNewstudent();
    Element ndestudent = (Element) currentstudents.getElementsByTagName("students").item(0);
    Node firstDocImportedNode = currentstudents.importNode(student, true);
    ndestudent.appendChild(firstDocImportedNode);
  }

  private static Document getCurrentstudents() throws Exception{
    DocumentBuilder builder = dbFactory.newDocumentBuilder();
    Document docstudent = builder.parse(new StringBufferInputStream(studentData));
    return docstudent;
  }

  private static Element getNewstudent() throws Exception{
    DocumentBuilder builder = dbFactory.newDocumentBuilder();
    Document newstudent = builder.parse(new StringBufferInputStream(studentData));
    Element student = newstudent.getDocumentElement();
    return student;
  }
}