Tuesday 21 October 2014

TransformerHandler : Send XML data to console


By using TransformerHandler you can create and send XML data to console.

Step 1: Get the instance of SAXTransformerFactory.
Ex: SAXTransformerFactory stf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();

Step 2: Get a TransformerHandler object.
Ex: TransformerHandler thd = stf.newTransformerHandler()

Step 3: Enable TransformerHandler to set the result for the transformation.
PrintStream writer = System.out;
StreamResult streamResult = new StreamResult(writer);       
thd.setResult(streamResult);

Step 4: Use TransformerHandler methods to create document, elements and attributes etc.,

Example
import java.io.PrintStream;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.SAXException;
import javax.xml.transform.Transformer;

public class GenerateXML {

    static TransformerHandler getHandler() throws TransformerConfigurationException{
        SAXTransformerFactory stf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        TransformerHandler thd = stf.newTransformerHandler();
        Transformer serializer = thd.getTransformer();
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        return thd;
    }

    public static void main(String args[]) throws TransformerConfigurationException, SAXException{
        TransformerHandler thd = getHandler();
        String id[] = {"1","2","3","4"};
        String name[] = {"Krishna", "Murali", "Susantha", "Shanmugham"};

        PrintStream writer = System.out;
        StreamResult streamResult = new StreamResult(writer);
        
        thd.setResult(streamResult);
        
        thd.startDocument();
        thd.startElement(null, null, "employees", null);

        for(int i=0; i<id.length; i++){
            thd.startElement("", "", "employee", null);

            thd.startElement("", "", "name", null);
            thd.characters(name[i].toCharArray(), 0, name[i].length());
            thd.endElement("", "", "name");

            thd.startElement("", "", "id", null);
            thd.characters(id[i].toCharArray(), 0, id[i].length());
            thd.endElement("", "", "id");

            thd.endElement("", "", "employee");
        }
        
        thd.endElement(null, null, "employees");
        thd.endDocument();
    }
}

Output 
<?xml version="1.0" encoding="UTF-8"?>
<employees>
<employee>
<name>Krishna</name>
<id>1</id>
</employee>
<employee>
<name>Murali</name>
<id>2</id>
</employee>
<employee>
<name>Susantha</name>
<id>3</id>
</employee>
<employee>
<name>Shanmugham</name>
<id>4</id>
</employee>
</employees>



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment