Java: How to Indent XML Generated by Transformer -


i'm using java's built in xml transformer take dom document , print out resulting xml. problem isn't indenting text @ despite having set parameter "indent" explicitly.

sample code

public class testxml {   public static void main(string args[]) throws exception {   bytearrayoutputstream s;    document d = documentbuilderfactory.newinstance().newdocumentbuilder().newdocument();   transformer t = transformerfactory.newinstance().newtransformer();    element a,b;    = d.createelement("a");   b = d.createelement("b");    a.appendchild(b);    d.appendchild(a);    t.setparameter(outputkeys.indent, "yes");    s = new bytearrayoutputstream();    t.transform(new domsource(d),new streamresult(s));    system.out.println(new string(s.tobytearray()));   } } 

result

<?xml version="1.0" encoding="utf-8" standalone="no"?><a><b/></a> 

desired result

<?xml version="1.0" encoding="utf-8" standalone="no"?> <a>  <b/> </a> 

thoughts?

you need enable 'indent' , set indent amount transformer:

t.setoutputproperty(outputkeys.indent, "yes"); t.setoutputproperty("{http://xml.apache.org/xslt}indent-amount", "2"); 

update:


reference : how strip whitespace-only text nodes dom before serialization?

(many members @marc-novakowski, @james-murty , @saad):


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -