my dog learned polymorphism
The moose likes XML and Related Technologies and the fly likes String to XML Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Engineering » XML and Related Technologies
Bookmark "String to XML" Watch "String to XML" New topic

String to XML

Gaurav Pawar
Ranch Hand

Joined: Sep 12, 2006
Posts: 37
I am new to XML parsing using Java. I wanted to know how can i convert a string that contains xml tags "<one><two>Gaurav</two></one>" into an xml document?

Also after i am done with that what is the best method(technology wise/parsers)to process/parse an xml document?

Gaurav Pawar
Ranch Hand

Joined: Sep 12, 2006
Posts: 37
Hi all,
Got it from some of the previous posts.

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


import org.w3c.dom.Document;

public class Hello {
String s="<hi><one>hello</one></hi>";

//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("PATH");
FileOutputStream fout = new FileOutputStream(f);

catch (Exception e) {
throw e;



public static void main(String[] args) throws Exception {
Hello h = new Hello();;
I agree. Here's the link:
subject: String to XML
It's not a secret anymore!