Converting to a String to XML Document

Tagged:
import java.io.IOException;
import java.io.StringReader;
 
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
 
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
 
 
/**
 * StringToXMLDoc.java
 * 
 * Example to convert String to XML Document object
 *
 *
 */
public class StringToXMLDoc {
	public static void main(String[] args) throws Exception {
 
 
		String sourceXMLString = "<contact><name>Duke</name><phone>123-456-789</phone> </contact>";
		StringReader reader = new StringReader(sourceXMLString);
		InputSource stringSource = new InputSource(reader);
 
 
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
 
		Document xmlDocument = builder.parse(stringSource);
 
 
		System.out.println(xmlDocument.getDocumentElement().getNodeName());
 
 
	}
}

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.