Create a xml document by creating xml element in Java

Description

The following code shows how to create a xml document by creating xml element.

Example


//  ww w  .ja va2  s  . c  om
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;

public class Main {

  public static void main(String[] argv) throws Exception{

      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      dbf.setNamespaceAware(true);
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.newDocument();

      Element root = doc.createElementNS(null, "Site"); 
      Element item = doc.createElementNS(null, "name"); 
      item.appendChild(doc.createTextNode("java2s.com"));
      root.appendChild(item); 
      item = doc.createElementNS(null, "topic"); 
      item.appendChild(doc.createTextNode("java"));
      root.appendChild(item);
      item = doc.createElementNS(null, "topic");
      item.appendChild(doc.createTextNode("xml"));
      root.appendChild(item);
      doc.appendChild(root);

      DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
      DOMImplementationLS domImplLS = (DOMImplementationLS) registry.getDOMImplementation("LS");

      LSSerializer ser = domImplLS.createLSSerializer();
                                                        
      LSOutput out = domImplLS.createLSOutput();
      StringWriter stringOut = new StringWriter();
      out.setCharacterStream(stringOut);
      ser.write(doc, out);

      System.out.println("STRXML = " + stringOut.toString());
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    XML »




DOM
SAX