Examples >

Write an XML File Programmatically

This example shows you how to create an XML file in Java using the XmlTemplate and and XmlWriter classes.

The demo code creates some test data in memory and creates an XML file out of this test data. However, an XML file can be created from other input data sources like Excel, Database, etc as well.

This example can easily be modified to show how to read an XML file or how to create an XML file using freemarker templates.

Java Code Listing

 * Copyright (c) 2006-2018 North Concepts Inc.  All rights reserved.
 * Proprietary and Confidential.  Use is subject to license terms.
 * http://northconcepts.com/data-pipeline/licensing/
package com.northconcepts.datapipeline.examples.cookbook;

import java.io.FileWriter;

import com.northconcepts.datapipeline.core.Record;
import com.northconcepts.datapipeline.core.RecordList;
import com.northconcepts.datapipeline.job.Job;
import com.northconcepts.datapipeline.memory.MemoryReader;
import com.northconcepts.datapipeline.xml.XmlWriter;
import com.northconcepts.datapipeline.xml.builder.XmlElement;
import com.northconcepts.datapipeline.xml.builder.XmlNodeContainer;
import com.northconcepts.datapipeline.xml.builder.XmlTemplate;

public class WriteAnXmlFileProgrammatically {

     * Produces the following XML (line breaks added for clarity)
     * <?xml version="1.0" encoding="UTF-8" standalone="no"?> <actors> <north-america> <actor stage-name="John Wayne" real-name=
     * "Marion Robert Morrison"> <gender>male</gender> <city>Winterset</city> <balance>156.35</balance> </actor> <actor
     * stage-name="Spiderman" real-name="Peter Parker"> <gender>male</gender> <city>New York</city> </actor> </north-america> </actors>

    public static void main(String[] args) throws Throwable {

        Record record1 = new Record();
        record1.setField("stageName", "John Wayne");
        record1.setField("realName", "Marion Robert Morrison");
        record1.setField("gender", "male");
        record1.setField("city", "Winterset");
        record1.setField("balance", 156.35);

        Record record2 = new Record();
        record2.getField("stageName", true).setValue("Spiderman");
        record2.getField("realName", true).setValue("Peter Parker");
        record2.getField("gender", true).setValue("male");
        record2.getField("city", true).setValue("New York");
        record2.getField("balance", true).setValue(-0.96);

        MemoryReader reader = new MemoryReader(new RecordList(record1, record2));

        // create the XML template
        // arguments to element(), attribute(), text(), and when() are expressions
        // literal strings must be quoted
        XmlTemplate template = new XmlTemplate();
        template.setDeclaration("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>");

        // detail() marks the node where records are added
        XmlNodeContainer detailElement = template.element("'actors'").element("'north-america'").detail();

        XmlElement actor = detailElement.element("'actor'");
        actor.attribute("'stage-name'", "stageName").attribute("'real-name'", "realName");
        actor.when("balance >= 0").element("'balance'").text("balance"); // add this branch when balance is not negative

        // add the template to the writer
        XmlWriter writer = new XmlWriter(template, new FileWriter("example/data/output/credit-balance-03.xml"))

        Job.run(reader, writer);


Code Walkthrough

  1. Two Record objects are created in memory with the fields stageName, realName,gender,city and balance set to some test values.
  2. A RecordList is created with these Record objects.
  3. A new MemoryReader is created to read this RecordList.
  4. The XML document structure corresponding to the input data is created using the XmlTemplate, XmlNodeContainer and XmlElement classes.
  5. A new XmlWriter is created corresponding to the XmlTemplate and the path of the output XML file credit-balance-03.xml.
  6. Data is transferred from memory to the output XML file via JobTemplate.DEFAULT.transfer method.

XML Creation

The following steps elaborate how the XML document is created (Step 4 above):

  1. An XmlTemplate is created corresponding to the output XML file and the XML declaration is added via template.setDeclaration.
  2. The template.element("'actors'") is invoked in order to create an XmlElement corresponding to the top level element i.e. actors.
  3. This XmlElement is in turn used to create a new XmlElement corresponding to north-america
  4. The element.detail method which specifies that this element has child elements is invoked and this returns an XmlNodeContainer.
  5. The XmlNodeContainer is used to create a new XmlElement corresponding to the actor field.
  6. The stage-name and real-name attributes are set on this element via the attribute method. This method accepts two String parameters, the first String specifies the name of the attribute in the output XML and the second String specifies the field name in the input Record object that should be used to get the value of this attribute.
  7. Since gender is a child of actor element, new XmlElement instance is created for this field via actor.element and the element.text method is invoked to specify the field name in the input Record object that should be used to get the value of this element.
  8. Similarly, an XmlElement is created for the city element.
  9. The actor.when method is used to create and add a balance field only when the balance is a non-negative value.

XmlTemplate and XmlElement

XmlTemplate and XmlElement are the main classes used to create the output XML. XmlTemplate is a high level abstraction which represents the entire XML document. XmlElement, represents an individual XML element.

Output XML file

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
		<actor stage-name="John Wayne" real-name="Marion Robert Morrison">
		<actor stage-name="Spiderman" real-name="Peter Parker">
			<city>New York</city>
Mobile Analytics