Pages

Sunday, November 14, 2010

Generate XML using SAX


import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
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 org.xml.sax.helpers.AttributesImpl;



.......

//generating XML file using SAX
SAXTransformerFactory fac = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
File outFile = new File("/test.xml");
OutputStream outStream = new FileOutputStream(outFile);
StreamResult resultxml = new StreamResult(outStream);


try {
String data=null;
//SAX ContentHandler
TransformerHandler handler = fac.newTransformerHandler();
handler.setResult(resultxml);

Transformer transformer = handler.getTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT,"yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");


//start the document

handler.startDocument();
AttributesImpl atts = new AttributesImpl();
atts.clear();
handler.startElement("", "", "Students", atts);
handler.startElement("", "", "Student", null);
        handler.startElement("""""ID"null);

data = "12345";
handler.characters(data.toCharArray(), 0, data.length());        handler.endElement("", "", "ID");
        handler.startElement("""""Name"null);
data = "John Smith";
handler.characters(data.toCharArray(), 0, data.length());        handler.endElement("""""Name");
handler.endElement("""""Student");

handler.endElement("""""Students");
handler.endDocument();
handler.setResult(resultxml);
outStream.close();


Genrated test.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Students>
<Student>
<ID>12345</ID>
<Name>John Smith</Name>
</Student>
</Stueents>



No comments:

Post a Comment