Search...
FAQs
Subscribe
Pie
FAQs
Recent topics
Flagged topics
Hot topics
Best topics
Search...
Search within Wiki
Search Coderanch
Advance search
Google search
Register / Login
Bookmark Topic
Watch Topic
programming forums
Java
Mobile
Certification
Databases
Caching
Books
Engineering
Micro Controllers
OS
Languages
Paradigms
IDEs
Build Tools
Frameworks
Application Servers
Open Source
This Site
Careers
Other
Pie Elite
all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Campbell Ritchie
Jeanne Boyarsky
Ron McLeod
Paul Clapham
Liutauras Vilda
Sheriffs:
paul wheaton
Rob Spoor
Devaka Cooray
Saloon Keepers:
Stephan van Hulst
Tim Holloway
Carey Brown
Frits Walraven
Tim Moores
Bartenders:
Mikalai Zaikin
Forums:
Wiki
XML and Related Technologies
How To Pretty Print Xml With Java
posted 8 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
Here's an example using the XMLSerializer class from Xerces:
import org.apache.xml.serialize.XMLSerializer; import org.apache.xml.serialize.OutputFormat; import org.w3c.dom.Document; import java.io.OutputStream; public class MyXmlPrettyPrinter { public void serialize(Document doc, OutputStream out) throws Exception { OutputFormat format = new OutputFormat(doc); format.setLineWidth(65); format.setIndenting(true); format.setIndent(2); XMLSerializer serializer = new XMLSerializer(out, format); serializer.serialize(doc); } }
Here's an example using the
JavaDoc:javax.xml.transformer.Transformer
:
import java.io.OutputStream; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; public class MyXmlPrettyPrinter2 { public void serialize(Document doc, OutputStream out) throws Exception { TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer serializer; try { serializer = tfactory.newTransformer(); //Setup indenting to "pretty print" serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); serializer.transform(new DOMSource(doc), new StreamResult(out)); } catch (TransformerException e) { // this is fatal, just dump the stack and throw a runtime exception e.printStackTrace(); throw new RuntimeException(e); } } }
XmlFaq
CategoryCodeSamples
Did you see how Paul
cut 87% off of his electric heat bill with 82 watts of micro heaters
?
Bookmark Topic
Watch Topic
New Topic
Boost this thread!
Similar Threads
Document Interface to a String
calling secured webservice from java by passing soap xml
What Replaced org.apache.xml.serialize.XMLSerializer and org.apache.xml.serialize.OutputFormat
DOM to string
setLineWidth() in OutputFormat class
More...