Save DOM Document to a file

In this chapter you will learn:

  1. How to save a DOM document to a file

Save a DOM Document

We can wrap StreamResult with a file name and output the DOM document to that file.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
//  j  a v  a  2  s .co  m
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
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 {
  private static void toString(Document newDoc) throws Exception{
    TransformerFactory tranFactory = TransformerFactory.newInstance();
    Transformer aTransformer = tranFactory.newTransformer();
    Source src = new DOMSource(newDoc);
    Result dest = new StreamResult(new File("xmlFileName.xml"));
    aTransformer.transform(src, dest);
  }
  public static void main(String[] args) throws Exception {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder domBuilder = domFactory.newDocumentBuilder();

    Document newDoc = domBuilder.newDocument();
    Element rootElement = newDoc.createElement("parent");
    newDoc.appendChild(rootElement);
    toString(newDoc);

  }

}

The content of the xmlFileName.xml.

Next chapter...

What you will learn in the next chapter:

  1. Format XML with Transformer
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