import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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 XmlTest {
public static void main(String[] args) throws Exception {
String xmlString = "<tag><nested>hello</nested></tag>";
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputStream inputStream = new ByteArrayInputStream(xmlString.getBytes());
Document document = documentBuilder.parse(inputStream);
XmlTest xmlTest = new XmlTest();
xmlTest.serialize(document, System.out);
}
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");
DOMSource xmlSource = new DOMSource(doc);
StreamResult outputTarget = new StreamResult(out);
serializer.transform(xmlSource, outputTarget);
} catch (TransformerException e) {
// this is fatal, just dump the stack and throw a runtime exception
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
Friday, September 26, 2008
Pretty Print XML in Java
Something I keep forgetting how to do. Obviously something would need to be done to make this any sort of utility class. This is simply an example of the classes that can be used to perform pretty print of an xml string. There are many more ways to get the actual string from a file or Document.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment