how to transform document to formatted XML file
0 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Rafal_Juszkiewicz
Posted On:   Friday, June 24, 2005 03:14 AM

have a question. I have written a sample java program that will create an xml file. The program works properly, but the generated xml is not formatted. How can i format the xml file. The java program code is package com.spi.xml; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; i   More>>

have a question. I have written a sample java program that will create an xml file. The program works properly, but the generated xml is not formatted. How can i format the xml file.


The java program code is


package com.spi.xml;


import java.io.File;


import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.transform.Result;

import javax.xml.transform.Source;

import javax.xml.transform.Transformer;

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.Element;



public class WriteXML {

static Document document;



public static void buildDOM() {



DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();

try {

DocumentBuilder builder = factory.newDocumentBuilder();

document = builder.newDocument();



Element root = (Element) document.createElement("GUI");

document.appendChild(root);



Element curElement = document.createElement("Button");

curElement.appendChild(document.createTextNode("Submit"));

root.appendChild(curElement);



curElement = document.createElement("Button");

curElement.appendChild(document.createTextNode("Cancel"));

root.appendChild(curElement);



// Save the document to the disk file

TransformerFactory tranFactory =
TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();



Source src = new DOMSource(document);

Result dest = new StreamResult(new
File("C:\xmlFileName.xml"));
aTransformer.transform(src, dest);



} catch (Exception pce) {

pce.printStackTrace();

}

}



public static void main(String[] args) {

buildDOM();

}

}






The output (XML file)



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






How can i format the xml file for multiple lines? I cant't use other libraries (Xerces,JDOM,Xalan) cause they are to big - the application is an applet.

   <<Less
About | Sitemap | Contact