In my earlier article, I have shown you how to create the XML file using java APIs. Here I will show you how to do the same however without actually creating files. Here I will use the String buffer to hold the XML content that can be used to do further processing if needed.
@Credit: Sumeet Chakraborty
Java API being used here is same as one earlier.
Another API being used:
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
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.Element;
public class XMLCreation {
public static void main(String args[]) {
XMLCreation xmlCreate = new XMLCreation();
xmlCreate.createXML();
}
private void createXML() {
String customerName = "Ramesh";
String customerAddress = "Delhi";
DocumentBuilder domBuilder = null;
try {
DocumentBuilderFactory domFactory = DocumentBuilderFactory
.newInstance();
domBuilder = domFactory.newDocumentBuilder();
} catch (ParserConfigurationException pcEx) {
System.out
.println("ParserConfiguration "
+ pcEx.getMessage());
} catch (Exception e) {
System.out
.println("Exception Occured"
+ e.getMessage());
}
Document newDoc = domBuilder.newDocument();
// Root element
Element rootElement = newDoc.createElement("CustomerInformation");
newDoc.appendChild(rootElement);
// Creating element containing value Name
Element curElement = newDoc.createElement("Name");
curElement.appendChild(newDoc.createTextNode(customerName));
rootElement.appendChild(curElement);
// Creating element signifies address
Element keyElement = newDoc.createElement("Address");
keyElement.appendChild(newDoc.createTextNode(customerAddress));
rootElement.appendChild(keyElement);
DOMSource sourceInt = new DOMSource(newDoc);
//This will hold the XML content being built later on
//This is the difference where we are not creating file
//Instead, we are using StringWriter to hold the XML content
StringWriter stew = new StringWriter();
// File stew = new File("C:/sampleXMLfile.xml");
StreamResult resultInt = new StreamResult(stew);
TransformerFactory tFactoryInt = TransformerFactory.newInstance();
Transformer transformerInt = null;
try {
transformerInt = tFactoryInt.newTransformer();
//this is where actually transformation happens and creates the XML
transformerInt.transform(sourceInt, resultInt);
System.out.println("XML created as " + stew.getBuffer().toString());
} catch (TransformerException tEx) {
System.out
.println("TransformerException Occured "
+ tEx.getMessage());
} catch (Exception e) {
System.out
.println("Exception Occured + e.getMessage());
}
}
}
No comments:
Post a Comment