📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
Development Process Steps
- The output create_jdom_users.xml File
- Program to create XML file in Java using JDOM Parser.
1. The output create_jdom_users.xml File
<?xml version="1.0" encoding="UTF-8"?>
<Users>
<User id="1">
<firstName>Ramesh</firstName>
<lastName>Fadatare</lastName>
<age>28</age>
<gender>Male</gender>
</User>
<User id="2">
<firstName>Tom</firstName>
<lastName>Cruise</lastName>
<age>45</age>
<gender>Male</gender>
</User>
<User id="3">
<firstName>Tony</firstName>
<lastName>Stark</lastName>
<age>40</age>
<gender>Male</gender>
</User>
<User id="3">
<firstName>Amir</firstName>
<lastName>Khan</lastName>
<age>50</age>
<gender>Male</gender>
</User>
</Users>
2. Program to create XML file in Java using JDOM Parser
package net.javaguides.javaxmlparser.jdom;
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 CreateXMLFile {
public static void main(String[] args) {
try {
Document doc = new Document();
doc.setRootElement(new Element("Users"));
doc.getRootElement().addContent(createUserXMLElement("1", "Ramesh", "Fadatare", "28", "Male"));
doc.getRootElement().addContent(createUserXMLElement("2", "Tom", "Cruise", "45", "Male"));
doc.getRootElement().addContent(createUserXMLElement("3", "Tony", "Stark", "40", "Male"));
doc.getRootElement().addContent(createUserXMLElement("3", "Amir", "Khan", "50", "Male"));
// new XMLOutputter().output(doc, System.out);
XMLOutputter xmlOutput = new XMLOutputter();
// xmlOutput.output(doc, System.out);
// display nice nice
xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(doc, new FileWriter("create_jdom_users.xml"));
System.out.println("File Saved!");
} catch (IOException io) {
System.out.println(io.getMessage());
}
}
private static Element createUserXMLElement(String id, String firstName, String lastName, String age,
String gender) {
Element user = new Element("User");
user.setAttribute(new Attribute("id", id));
user.addContent(new Element("firstName").setText(firstName));
user.addContent(new Element("lastName").setText(lastName));
user.addContent(new Element("age").setText(age));
user.addContent(new Element("gender").setText(gender));
return user;
}
}
Comments
Post a Comment
Leave Comment