[java] 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>

This question is related to java xml xml-parsing

The answer is


public static void main(String[] args) {

try {

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.newDocument();
    Element rootElement = doc.createElement("CONFIGURATION");
    doc.appendChild(rootElement);
    Element browser = doc.createElement("BROWSER");
    browser.appendChild(doc.createTextNode("chrome"));
    rootElement.appendChild(browser);
    Element base = doc.createElement("BASE");
    base.appendChild(doc.createTextNode("http:fut"));
    rootElement.appendChild(base);
    Element employee = doc.createElement("EMPLOYEE");
    rootElement.appendChild(employee);
    Element empName = doc.createElement("EMP_NAME");
    empName.appendChild(doc.createTextNode("Anhorn, Irene"));
    employee.appendChild(empName);
    Element actDate = doc.createElement("ACT_DATE");
    actDate.appendChild(doc.createTextNode("20131201"));
    employee.appendChild(actDate);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File("/Users/myXml/ScoreDetail.xml"));
    transformer.transform(source, result);
    System.out.println("File saved!");
  } catch (ParserConfigurationException pce) {
    pce.printStackTrace();
  } catch (TransformerException tfe) {
    tfe.printStackTrace();}}

The values in you XML is Hard coded.


Use JAXB: http://www.mkyong.com/java/jaxb-hello-world-example/

package com.mkyong.core;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

}
package com.mkyong.core;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {
    public static void main(String[] args) {

      Customer customer = new Customer();
      customer.setId(100);
      customer.setName("mkyong");
      customer.setAge(29);

      try {

        File file = new File("C:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(customer, file);
        jaxbMarshaller.marshal(customer, System.out);

      } catch (JAXBException e) {
        e.printStackTrace();
      }

    }
}

There is no need for any External libraries, the JRE System libraries provide all you need.

I am infering that you have a org.w3c.dom.Document object you would like to write to a file

To do that, you use a javax.xml.transform.Transformer:

import org.w3c.dom.Document
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult; 

public class XMLWriter {
    public static void writeDocumentToFile(Document document, File file) {

        // Make a transformer factory to create the Transformer
        TransformerFactory tFactory = TransformerFactory.newInstance();

        // Make the Transformer
        Transformer transformer = tFactory.newTransformer();

        // Mark the document as a DOM (XML) source
        DOMSource source = new DOMSource(document);

        // Say where we want the XML to go
        StreamResult result = new StreamResult(file);

        // Write the XML to file
        transformer.transform(source, result);
    }
}

Source: http://docs.oracle.com/javaee/1.4/tutorial/doc/JAXPXSLT4.html


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to xml

strange error in my Animation Drawable How do I POST XML data to a webservice with Postman? PHP XML Extension: Not installed How to add a Hint in spinner in XML Generating Request/Response XML from a WSDL Manifest Merger failed with multiple errors in Android Studio How to set menu to Toolbar in Android How to add colored border on cardview? Android: ScrollView vs NestedScrollView WARNING: Exception encountered during context initialization - cancelling refresh attempt

Examples related to xml-parsing

How to create XML file with specific structure in Java jQuery xml error ' No 'Access-Control-Allow-Origin' header is present on the requested resource.' SyntaxError of Non-ASCII character xml.LoadData - Data at the root level is invalid. Line 1, position 1 XML Error: Extra content at the end of the document How to use sed to extract substring How to fix Invalid byte 1 of 1-byte UTF-8 sequence The best node module for XML parsing Parsing XML with namespace in Python via 'ElementTree' oracle plsql: how to parse XML and insert into table