XMLドキュメントを作成し、JVM組み込みライブラリを使用してインデントされた形式で印刷しています。改行を含むテキストノードがドキュメントにある場合、適切なインデント位置ではなく、行を行の先頭に折り返します
サンプルコード
ByteArrayOutputStream s;
s = new ByteArrayOutputStream();
Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Transformer t = TransformerFactory.newInstance().newTransformer();
Element a;
Text b;
a = d.createElement("a");
String text = "multi\nline\ntext";
b = d.createTextNode(text);
a.appendChild(b);
d.appendChild(a);
t.setOutputProperty(OutputKeys.INDENT,"yes");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
t.transform(new DOMSource(d), new StreamResult(s));
System.out.println(new String(s.toByteArray()));
出力
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<a>multi
line
text</a>
希望する出力
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<a>
multi
line
text
</a>
インデントされたxmlタグが始まる場所から新しい各行を開始するスマートな方法はありますか?textnodeを使用するのは適切ではないということを教えてくれますか?もっと良いものはありますか?