Skip to content

Instantly share code, notes, and snippets.

@wbotelhos
Created July 18, 2012 21:07
Show Gist options
  • Select an option

  • Save wbotelhos/3138905 to your computer and use it in GitHub Desktop.

Select an option

Save wbotelhos/3138905 to your computer and use it in GitHub Desktop.
DOM Document to String
<?xml version="1.0" encoding="UTF-8"?>
<blogs>
<blog>
<author>Washington Botelho</author>
<url>http://wbotelhos.com.br</url>
<language>pt_BR</language>
</blog>
<blog>
<author>Washington Botelho</author>
<url>http://wbotelhos.com</url>
<language>en_US</language>
</blog>
</blogs>
import java.io.File;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
public class Program {
public static void main(String args[]) throws Exception {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = builder.parse(new File("blogs.xml"));
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(writer));
System.out.println(writer.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment