Writing an xml document to a file & indent it

Writing an xml document to a file & indent itSocialTwist Tell-a-Friend

Heres a simple code snippet in java for writing an xml document created
to an xml file.
Seems quite a common task but had to google quite a bit to get it right ....



Document doc = null; // load your DOM into this document object

TransformerFactory transfactory = TransformerFactory.newInstance();

Transformer transformer = transfactory.newTransformer();

StringWriter writer = new StringWriter();
StreamResult destination = new StreamResult(writer);
DOMSource source = new DOMSource(doc);

transformer.transform(source, destination);

String xmlString = writer.toString();

OutputStream os;

byte buf[] = xmlString.getBytes();
os = new FileOutputStream("output.xml");

for(int i=0;i
os.write(buf[i]);
}

os.close();
buf = null;




Modifications to the code so that the output xml file is properly indented.



TransformerFactory transfactory = TransformerFactory.newInstance();

// code for indenting
transfactory.setAttribute("indent-number", new Integer(2));

Transformer transformer = transfactory.newTransformer();

// code for indenting
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

0 comments:

Post a Comment

BlogCatalog

Travel Blogs - BlogCatalog Blog Directory