user3438838 user3438838 - 5 months ago 19
Java Question

How to create XML file with specific structure in Java

I would like to create

XML
file using
Java
.

My
XML
file structure:

<?xml version="1.0" encoding="UTF-8"?>
<CONFIGURATION>
<BROWSER>chrome</BROWSER>
<BASE>http:fut</BASE>
<ENVIRONMENT>abcd</ENVIRONMENT>
<USER>john</USER>
<PASSWORD>abcd123</PASSWORD>
<ORGANIZATION>Tim</ORGANIZATION>
<EMPLOYEE>
<EMP_NAME>Anhorn, Irene</EMP_NAME>
<ACT_DATE>20131201</ACT_DATE>
<DATE_IN>20131201</DATE_IN>
<CLOCK_IN>0800</CLOCK_IN>
<DATE_OUT>20131201</DATE_OUT>
<CLOCK_OUT>1600</CLOCK_OUT>
</EMPLOYEE>
<EMPLOYEE>
<EMP_NAME>Arlegui, Karen Jay</EMP_NAME>
<ACT_DATE>20131201</ACT_DATE>
<DATE_IN>20131201</DATE_IN>
<CLOCK_IN>1600</CLOCK_IN>
<DATE_OUT>20131202</DATE_OUT>
<CLOCK_OUT>0000</CLOCK_OUT>
</EMPLOYEE>
</CONFIGURATION>

Answer

You can use the JDOM library in Java. Define your tags as Element objects, document your elements with Document Class, and build your xml file with SAXBuilder. Try this example:

Element root=new Element("CONFIGURATION");
Document doc=new Document();

Element child1=new Element("BROWSER");
child1.addContent("chrome");
Element child2=new Element("BASE");
child1.addContent("http:fut");
Element child3=new Element("EMPLOYEE");
child3.addContent(new Element("EMP_NAME").addContent("Anhorn, Irene"));

root.addContent(child1);
root.addContent(child2);
root.addContent(child3);

doc.setRootElement(root);

XMLOutputter outter=new XMLOutputter();
outter.setFormat(Format.getPrettyFormat());
outter.output(doc, new FileWriter(new File("myxml.xml")));