漫不經心的憂傷,踹到JDOM來。拿既有的Element當作一份新產出XML Document怎麼處理呢?假設Element值是<book>漫不經心</book>,若要以<book>為根元素,其寫法如下:

XMLOutputter outputter = new XMLOutputter();
fos = new FileOutputStream(filename);
Document doc = new Document(element.detach());
outputter.output(doc, fos);
fos.flush();
fos.close();

  而若想在<book>之上再有個<root>作為根元素,則寫法如下:

XMLOutputter outputter = new XMLOutputter();
fos = new FileOutputStream(filename);
Element root = new Element("root");
Document doc = new Document(root);
root.addContent(element.detach());
outputter.output(doc, fos);
fos.flush();
fos.close();

  沒辦法將Element物件當作內容被加到addContent,需用detach複製自己。否則常有以下的Exception:

org.jdom.IllegalAddException: The Content already has an existing parent "root"

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 Jemmy 的頭像
    Jemmy

    Jemmy Walker

    Jemmy 發表在 痞客邦 留言(0) 人氣()