In this example we will show how to create XML file in Java.
Source Code
package com.beginner.examples;
import java.io.FileWriter;
import java.io.IOException;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
public class CreateXML {
public static void main(String[] args) throws IOException {
Element student = new Element("student");
Document document = new Document(student);
document.setRootElement(student);
Element person = new Element("person");
person.setAttribute(new Attribute("id", "10000"));
person.addContent(new Element("name").setText("Alice"));
person.addContent(new Element("age").setText("18"));
document.getRootElement().addContent(person);
XMLOutputter xmlOutput = new XMLOutputter();
xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(document, new FileWriter("e:tmptest.xml"));
System.out.println("create successfully");
}
}
Output:
create successfully
References
Imported packages in Java documentation: