In this tutorial you will learn how to write to file dom document. Write to xml file you would be required to use the package javax.xml. This package provides the facility to create XML file easily.
Java Write To File Dom Document
In this tutorial you will learn how to write to file dom document.
Write to xml file you would be required to use the package javax.xml. This package provides the facility to create XML file easily.
Here I am giving a simple example which will demonstrate you how to write to xml file. At first I have created a new file using the class File of java.io package. In the example that I have used describing as follows :
Document interface of org.w3c.dom package represents the whole HTML or XML document as a root of the document tree that provides the preliminary accesses to the data of document. Source interface keeps the information that is required to act as source input. DOMSource class is a transformation source tree holder. Transformer is an abstract class that can transforms a source tree into a result tree. TransformerFactory is an abstract class which instance is used to create Transformer object (in this example). Result is an interface that holds the information required to construct a transformation result tree. StreamResult is a class that that works as a holder for transformation result.
Example :
WriteToFileDomDocument.java
import java.io.File; 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; public class WriteToFileDomDocument{ public static void main(String[] args) throws Exception { Document doc = null; Source src= new DOMSource(doc); File file = new File("writeToFileDomDocument"); Result rs = new StreamResult(file); TransformerFactory tmf = TransformerFactory.newInstance(); Transformer trnsfrmr = tmf.newTransformer(); trnsfrmr.transform(src, rs); System.out.println("XML file is created successfully"); } }
How to Execute this example :
After doing the basic process to execute a java program write simply on command prompt as :
javac WriteToFileDomDocument.java to compile the program
And after successfully compilation to run simply type as :
java WriteToFileDomDocument
Output :
When you will execute this example a file will be created on the specified place as the path given by you when you will open this file with notepad the output will be as :