Sunday, January 28, 2007

Converting String to XML

Actually for one of requirements I was looking for some piece of code that will actually parse String xml(Example - "Gaurav" )into XML.

I found the code in JavaRanch. For my convinience I am saving it here also.

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.StringWriter;

import org.apache.commons.configuration.XMLConfiguration;
import org.w3c.dom.Document;

public class Hello {
String s = "hello";

// create an input stream
ByteArrayInputStream xmlIn = new ByteArrayInputStream(s.getBytes());

// get a document builder from the pool

public void build() throws Exception {
try {
DocumentBuilderFactory domFactory = DocumentBuilderFactory
.newInstance();

DocumentBuilder builder = domFactory.newDocumentBuilder();

Document doc = builder.parse(xmlIn);

StringWriter output = new StringWriter();
TransformerFactory.newInstance().newTransformer().transform(
new DOMSource(doc), new StreamResult(output));

File f = new File("c:/test/something.xml");
FileOutputStream fout = new FileOutputStream(f);
fout.write(output.toString().getBytes());

} catch (Exception e) {
throw e;
}
}

Hello() {

}

public static void main(String[] args) throws Exception {
Hello h = new Hello();
h.build();
}
}

Thursday, January 18, 2007

I am back

From the beginning I want to improve my english writing skills. But it never worked in my way. So I will try to improve that by righting some english blog. As I am right now concentrating more in Java/J2EE. I will post some articles in java.

May be this is helpful for the beginners. Let me try my level best.

From today I will try to blog once in a week.

public class WelcomeBack {

public static void main(String args[]) {

System.out.println("Welcome Back Buddy.");

}
}