top of page

Serialize DOM to a String/File and transform using TrAX

 

1. Let us start with the source code of previous example. 

2. Goto the main method and comment the below lines. 

 

// Node root = doc.getFirstChild();

// System.out.println(root.getNodeName());

//    NodeList nodes = root.getChildNodes();

//    for (int i = 0; i < nodes.getLength(); i++) {

//     Node child = nodes.item(i);

//     System.out.println(child.getNodeName());

//     System.out.println(child.getTextContent());

// }

 

 

3. The steps are as below. 

  •  create a DOMSource object 

  •  create a StringWriter object to write the output

  •  create a StreamResult object to stream it to the writer object. 

  •  create a factory object using TransformerFactory class

  •  create a transformer object using the Transformer class and the factory object. 

 

This will be the code. 

 

        DOMSource source = new DOMSource(doc);

        StringWriter writer = new StringWriter();

        StreamResult result = new StreamResult(writer);

        TransformerFactory factory = TransformerFactory.newInstance();

        Transformer transformer = factory.newTransformer();

 

4. Use the below code to print the xml string. 

 

        transformer.transform(source, result);

        String xmlString = writer.toString();

        System.out.println(xmlString);

 

The output will have no indentation or spaces. It will be like this. 

 

<?xml version="1.0" encoding="UTF-8" standalone="no"?><items id="5"><item> <name>iPhone 5 </name><manufacturer>Apple Inc </manufacturer><price>600 </price></item><item> <name>iPhone 6 </name><manufacturer>Apple Inc </manufacturer><price>700 </price></item><item> <name>Moto X </name><manufacturer>Motorola </manufacturer><price>200 </price></item><item> <name>Moto G </name><manufacturer>Motorola </manufacturer><price>450 </price></item><item> <name>Samsung S4 </name><manufacturer>Samsung Corp </manufacturer><price>550 </price></item></items>

 

5. But the transformer comes with some properties that could make this work better. 

    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

 

Now the output will be like 

 

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<items id="5">

  <item> <name>iPhone 5 </name>

    <manufacturer>Apple Inc </manufacturer>

    <price>600 </price>

  </item>

  <item> <name>iPhone 6 </name>

    <manufacturer>Apple Inc </manufacturer>

    <price>700 </price>

  </item>

  <item> <name>Moto X </name>

    <manufacturer>Motorola </manufacturer>

    <price>200 </price>

  </item>

  <item> <name>Moto G </name>

    <manufacturer>Motorola </manufacturer>

    <price>450 </price>

  </item>

  <item> <name>Samsung S4 </name>

    <manufacturer>Samsung Corp </manufacturer>

    <price>550 </price>

  </item>

</items>

 

 

Below is the code for the reference. 

 

 

package com.javatweaks.dom;

 

import java.io.File;

import java.io.IOException;

import java.io.StringWriter;

import java.util.List;

 

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException;

import javax.xml.transform.OutputKeys;

import javax.xml.transform.Transformer;

import javax.xml.transform.TransformerConfigurationException;

import javax.xml.transform.TransformerException;

import javax.xml.transform.TransformerFactory;

import javax.xml.transform.dom.DOMSource;

import javax.xml.transform.stream.StreamResult;

 

import org.w3c.dom.Document;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

 

import com.javatweaks.sax.read.Items;

import com.javatweaks.sax.read.SAXItemsHandler;

 

public class DOMCreator {

 

    

    public static void main(String[] args) throws ParserConfigurationException, IOException, TransformerException {

        

        String filename = "C:\\Users\\xxxx\\Documents\\Java_XML\\items.xml";

        SAXItemsHandler saxHandler = new SAXItemsHandler();

        List<Items> data = saxHandler.readDataFromXML(filename);

 

        createXMLDOM dom = new createXMLDOM();

        Document doc = dom.createXMLDOC(data);

        

        DOMSource source = new DOMSource(doc);

        StringWriter writer = new StringWriter();

        StreamResult result = new StreamResult(writer);

        TransformerFactory factory = TransformerFactory.newInstance();

        Transformer transformer = factory.newTransformer();

        

        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        

        transformer.transform(source, result);

        String xmlString = writer.toString();

        System.out.println(xmlString);

        

//        Node root = doc.getFirstChild();

//        System.out.println(root.getNodeName());

//        NodeList nodes = root.getChildNodes();

//        for (int i = 0; i < nodes.getLength(); i++) {

//                Node child = nodes.item(i);

//                System.out.println(child.getNodeName());

//                System.out.println(child.getTextContent());

//        }

        

 

    }

}

 

 

 

 

Now let us refactor this code and write the string to a file. 

 

1. Remove all the commented lines. Select the below 4 lines and Refactor .

 

TransformerFactory factory = TransformerFactory.newInstance();

Transformer transformer = factory.newTransformer();

transformer.setOutputProperty(OutputKeys.INDENT, "yes");

transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

 

We will come up with a method 

 

Transformer transformer = getTransformer();

 

2. Now let us refactor the next piece of code. 

 

DOMSource source = new DOMSource(doc);

StringWriter writer = new StringWriter();

StreamResult result = new StreamResult(writer);

Transformer transformer = getTransformer();

transformer.transform(source, result);

String xmlString = writer.toString();

System.out.println(xmlString);

 

We will come up with a method. 

 

transformDOMtoString(doc);

 

 

3. Create a new class writeToFile() with Document and String as inputs. 

The source code will be as below. The highlighted code are new or refactored. 

 

 

package com.javatweaks.dom;

 

import java.io.File;

import java.io.IOException;

import java.io.StringWriter;

import java.util.List;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException;

import javax.xml.transform.OutputKeys;

import javax.xml.transform.Transformer;

import javax.xml.transform.TransformerConfigurationException;

import javax.xml.transform.TransformerException;

import javax.xml.transform.TransformerFactory;

import javax.xml.transform.TransformerFactoryConfigurationError;

import javax.xml.transform.dom.DOMSource;

import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

import com.javatweaks.sax.read.Items;

import com.javatweaks.sax.read.SAXItemsHandler;

 

public class DOMCreator {

    

    public static void main(String[] args) throws ParserConfigurationException, IOException, TransformerException {

        

        String filename = "C:\\Users\\xxxxx\\Documents\\Java_XML\\items.xml";

        SAXItemsHandler saxHandler = new SAXItemsHandler();

        List<Items> data = saxHandler.readDataFromXML(filename);

        createXMLDOM dom = new createXMLDOM();

        Document doc = dom.createXMLDOC(data);

        transformDOMtoString(doc);

        writeToFile(doc, "./output/items.xml");

 

    }

 

    public static void transformDOMtoString(Document doc)

            throws TransformerFactoryConfigurationError,

            TransformerConfigurationException, TransformerException {

        DOMSource source = new DOMSource(doc);

        StringWriter writer = new StringWriter();

        StreamResult result = new StreamResult(writer);

        Transformer transformer = getTransformer();

        transformer.transform(source, result);

        String xmlString = writer.toString();

        System.out.println(xmlString);

    }

    

    public static void writeToFile(Document doc, String filename) throws TransformerConfigurationException, TransformerException, TransformerFactoryConfigurationError {

        DOMSource source = new DOMSource(doc);

        StreamResult result = new StreamResult(new File(filename));

        getTransformer().transform(source, result);

        

    }

 

    public static Transformer getTransformer()

            throws TransformerFactoryConfigurationError,

            TransformerConfigurationException {

        TransformerFactory factory = TransformerFactory.newInstance();

        Transformer transformer = factory.newTransformer();

        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        return transformer;

    }

}

 

 

Now run the program and you will see that the items.xml will get generated. Make sure that you create a folder named output in the project. 

 

 

bottom of page