Bir XML dökümanının hiyerarşik yapısını biçimlendirip output'a veya bir dosyaya yazabilirsiniz. Bunun için TransformerFactory sınıfında OutputProperty değerleri kullanılır. Aşağıda bu işi yapan basit bir örnek görülmektedir :
public class XmlOutputPropertyTest {
public static void main(String[] args)
throws UnsupportedEncodingException,
TransformerFactoryConfigurationError, TransformerException {
String xml="<test><message id=\"123\"><b>World</b></message><detail>Detay bilgisi burada</detail></test>";
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // xml declarasyonu istemiyoruz
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
StringReader reader=new StringReader(xml);
StreamSource source =new StreamSource(reader);
StreamResult result= new StreamResult(new OutputStreamWriter(System.out, "UTF-8"));
transformer.transform(source , result);
}
}
Bu uygulama çalıştığında standart output (çıktı) ekranında XML biçimli bir şekilde gözükecektir :
<test>
<message id="123">
<b>World</b>
</message>
<detail>Detay bilgisi burada</detail>
</test>
XML'i biçimlenmesi aşağıdaki kod bölümü sağlamaktadır :
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // xml declarasyonu istemiyoruz
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
Eğer bu satırları yorum haline getirip tekrar çalıştırırsak çıktı aşağıdaki gibi olacaktır :
<?xml version="1.0" encoding="UTF-8"?>
<test>
<message id="123"><b>World</b></message>
<detail>Detay bilgisi burada</detail>
</test>