2013-05-16 303 views
1

是否可以从Transformer对象格式化输出XML文件?使用Transformer格式化输出XML

截至目前,我得到这些作为输出:

<A name="a" type="a"> 
    <B name="b" type="b" width="100" height="100" /> 
    <B name="b" type="b" width="100" height="200" /> 
    <B name="b" type="b" width="100" height="300" /> 
    <B name="b" type="b" width="100" height="400" /> 
</A> 

但我想,看起来是这样的:

<A name="a" 
    type="a"> 
    <B name="b" 
     type="b" 
     width="100" 
     height="100" /> 
    <B name="b" 
     type="b" 
     width="100" 
     height="200" /> 
    <B name="b" 
     type="b" 
     width="100" 
     height="300" /> 
    <B name="b" 
     type="b" 
     width="100" 
     height="400" /> 
</A> 

这里是我的变压器的代码片段:

TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
Transformer transformer = transformerFactory.newTransformer(); 
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
DOMSource source = new DOMSource(doc); 
StreamResult result = new StreamResult(file); 
transformer.transform(source, result); 

回答

0

我会在tmp文件中保存xml,然后逐行读取它并保存。例如,对于一个线

String line = " <B name=\"b\" type=\"b\" width=\"100\" height=\"100\" />"; 
    String indent = line.startsWith("<A") ? " " : "  "; 
    line = line.replaceAll("(type|width|height)", "\n" + indent + "$1"); 
    System.out.println(line); 

输出

<B name="b" 
    type="b" 
    width="100" 
    height="100" /> 
+0

有其他的方式来做到这一点?我的意思。只有当我拥有的属性限于type | width | height时,它才会起作用,对吗?但是如果我不知道这些属性是什么的话呢?谢谢btw。 – kishidp

+0

SAX可以提供帮助,但它会是一大块代码。 –