Skip to content

Instantly share code, notes, and snippets.

@mnuessler
Created December 30, 2012 12:38
Show Gist options
  • Save mnuessler/4412641 to your computer and use it in GitHub Desktop.
Save mnuessler/4412641 to your computer and use it in GitHub Desktop.
Snippets for working with XML in Java
public final class DomUtil {
private DomUtil() {
// prevent instantiation
}
public static Document stringToDocument(String xml) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
InputSource input = new InputSource(new StringReader(xml));
return factory.newDocumentBuilder().parse(input);
}
public static String documentToString(Document doc) throws TransformerException {
DOMSource source = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.transform(source, result);
return writer.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment