Java Program To Create XML File
Chapter:
Miscellaneous
Last Updated:
23-04-2023 04:50:46 UTC
Program:
/* ............... START ............... */
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class XMLCreator {
public static void main(String[] args) {
try {
// Create a new DocumentBuilderFactory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Create a new DocumentBuilder
DocumentBuilder builder = factory.newDocumentBuilder();
// Create a new Document
Document doc = builder.newDocument();
// Create the root element
Element root = doc.createElement("root");
doc.appendChild(root);
// Create a child element and add it to the root
Element child = doc.createElement("child");
child.appendChild(doc.createTextNode("This is the child element"));
root.appendChild(child);
// Create another child element and add it to the root
Element child2 = doc.createElement("child2");
child2.appendChild(doc.createTextNode("This is the second child element"));
root.appendChild(child2);
// Write the Document to a file
File file = new File("example.xml");
javax.xml.transform.TransformerFactory.newInstance().newTransformer().transform(
new javax.xml.transform.dom.DOMSource(doc),
new javax.xml.transform.stream.StreamResult(file)
);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/* ............... END ............... */
Output
<root>
<child>This is the child element</child>
<child2>This is the second child element</child2>
</root>
Notes:
-
The Java program creates an XML file using the Java programming language.It starts by importing the necessary classes from the javax.xml.parsers and org.w3c.dom packages. These classes provide a way to work with XML data in Java.
- The program then creates a new DocumentBuilderFactory and a new DocumentBuilder, which we use to create a new Document object that represents an XML document.
- The program creates a root element called root using the createElement method of the Document object and appends it to the document using the appendChild method. It then creates two child elements called child and child2, sets their text content using the createTextNode method, and appends them to the root element using the appendChild method.
- Finally, the program writes the Document object to a file called example.xml using the javax.xml.transform.TransformerFactory class, which provides a way to transform an XML document into various output formats.
- The resulting XML file has a root element called root with two child elements called child and child2, each with their respective text content.
Tags
java program to create xml file # How to create XML file in Java # Read and write XML file in Java