XMLEncoder は、Bean をテキストとしてエンコードするための汎用ユーティリティです。あなたの場合には適していないと思います。
あなたのニーズをよく理解していると仮定して、仕事をするコードを書きました。ツリー モデルをパラメーターとして toXml メソッドに渡すだけです。これは単なるドラフトであることに注意してください。おそらく、例外を別の方法で処理し、変換パラメーターを別の方法で管理したいと思うでしょう。さらに重要なことは、再帰的な createTree メソッドを操作して、ツリー ノードごとに作成される XML ノードの構造を変更できることです。
public static String toXml(TreeModel model) throws ParserConfigurationException, TransformerException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
DOMImplementation impl = builder.getDOMImplementation();
// Build an XML document from the tree model
Document doc = impl.createDocument(null,null,null);
Element root = createTree(doc, model, model.getRoot());
doc.appendChild(root);
// Transform the document into a string
DOMSource domSource = new DOMSource(doc);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter sw = new StringWriter();
StreamResult sr = new StreamResult(sw);
transformer.transform(domSource, sr);
return sw.toString();
}
private static Element createTree(Document doc, TreeModel model, Object node) {
Element el = doc.createElement(node.toString());
for(int i=0;i<model.getChildCount(node);i++){
Object child = model.getChild(node, i);
el.appendChild(createTree(doc,model,child));
}
return el;
}