App下載
首頁javadomJava HTML/XML - 如何append元素

Java HTML/XML - 如何append元素

我們想知道如何append元素。
import java.io.ByteArrayOutputStream;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

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

public class Main {
  public static Document userdom;
  public static void main(String[] args) throws Exception {
    userdom = DocumentBuilderFactory.newInstance().newDocumentBuilder()
        .newDocument();
    Element root = userdom.createElement("users");
    Node adoptNode = userdom.adoptNode(root);
    userdom.appendChild(adoptNode);
    Element e = userdom.createElement("user");

    e.setAttribute("id", "blah");
    e.setAttribute("username", "kermit");
    e.setAttribute("password", "bunnies in the air");
    e.setAttribute("login", "kermmi");

    userdom.getFirstChild().appendChild(e);
    System.out.println(e);
    System.out.println(userdom.getFirstChild() + "|"
        + userdom.getFirstChild().getFirstChild());
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer trans = tf.newTransformer();
    System.out.println(userdom.getFirstChild() + "|"
        + userdom.getFirstChild().getFirstChild());
    DOMSource ds = new DOMSource(userdom);

    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
      StreamResult sr = new StreamResult(baos);
      trans.transform(ds, sr);
      System.out.println(new String(baos.toByteArray()));
    }
  }
}