App下載
首頁javadomJava HTML/XML - 如何將節(jié)點從xml文檔附加到現(xiàn)有xml文檔

Java HTML/XML - 如何將節(jié)點從xml文檔附加到現(xiàn)有xml文檔

我們想知道如何將節(jié)點從xml文檔附加到現(xiàn)有xml文檔。
import java.io.StringBufferInputStream;

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