DOMImplementation

In this chapter you will learn:

  1. How to use DOMImplementation

Using DOMImplementation

import java.io.StringWriter;
/*java 2s .c  om*/
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.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Main {
  public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    DOMImplementation impl = builder.getDOMImplementation();
    Document doc = impl.createDocument(null, null, null);
    Element e1 = doc.createElement("api");
    doc.appendChild(e1);
    Element e2 = doc.createElement("java");
    e1.appendChild(e2);

    DOMSource domSource = new DOMSource(doc);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    StringWriter sw = new StringWriter();
    StreamResult sr = new StreamResult(sw);
    transformer.transform(domSource, sr);
    System.out.println(sw.toString());
  }
}

Next chapter...

What you will learn in the next chapter:

  1. SAX parer with all its action displayed
Home » Java Tutorial » XML

DOM Parser

    DOM
    Parse XML string
    Parse XML file with DOM Parser
    DOM Parser Error
    Output DOM Document to console
    Save DOM Document to a file
    Format a DOM Document
    Output Document to String
    Visit all elements
    Element retrieve by tag name
    Element character data retrieve
    DOM node visiting
    Node type
    DOM node dump
    Children nodes
    Root Element
    Doc Type
    Declared Entities
    External Entities resolve
    DOMImplementation

DOM Edit

    Element text child data
    Element remove
    Add text node to element
    Element text data update
    Add attribute to element
    Attribute remove
    Create new empty element
    Element clone
    CDATASection
    Comments element
    Processing Instruction
    New XML Document

SAX Parser

    SAX Parser action
    Parse an XML file with SAX parser
    SAX Parser based XML Document dump
    SAX Parser Error Handler
    SAX Parser content handler
    SAX Locator

Utility

    Encode String for XML attribute
    Convert Source to InputSource