App下載
首頁(yè)javadomJava HTML/XML - 如何將節(jié)點(diǎn)附加到現(xiàn)有XML文件

Java HTML/XML - 如何將節(jié)點(diǎn)附加到現(xiàn)有XML文件

我們想知道如何將節(jié)點(diǎn)附加到現(xiàn)有XML文件。
import java.util.ArrayList;
import java.util.Collection;

import javax.xml.parsers.DocumentBuilder;
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;

public class Main {
  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();
    Element rootElement = document.getDocumentElement();

    Collection<Server> svr = new ArrayList<Server>();
    svr.add(new Server());

    for (Server i : svr) {
      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);

      root.appendChild(server);
    }

    DOMSource source = new DOMSource(document);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    StreamResult result = new StreamResult("server.xml");
    transformer.transform(source, result);
  }

}
class Server {
  public String getName() {
    return "foo";
  }

  public Integer getPort() {
    return 12345;
  }
}