Created
December 30, 2012 12:38
-
-
Save mnuessler/4412641 to your computer and use it in GitHub Desktop.
Snippets for working with XML in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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