// 把DOM转为String
private String otputDOMToXMLString(Document doc) throws IOException {
String XMLString = "";
//建立dom的输出格式
OutputFormat format = new OutputFormat(doc);
StringWriter stringOut = new StringWriter();
XMLSerializer serial = new XMLSerializer(stringOut, format);
serial.asDOMSerializer();
serial.serialize(doc.getDocumentElement());
XMLString = stringOut.toString();
System.out.println(XMLString);
return XMLString;
}

 //把String 保存为文件 
private void saveXMLString(String XMLString, String fileName)
throws IOException {
File file = new File(fileName);
if (file.exists()) {
file.delete();
}

file.createNewFile();
if (file.canWrite()) {
FileWriter fileOut = new FileWriter(file);
fileOut.write(XMLString);
fileOut.close();
}
}

解决方案 »

  1.   

    这都是什么类啊,怎么都没见过,JavaDoc里面查不到!
      

  2.   

    用Jdom吧,很简单的.
    www.jdom.org
      

  3.   

    import java.io.IOException;import org.jdom.Document;
    import org.jdom.Element;
    import org.jdom.output.Format;
    import org.jdom.output.XMLOutputter;
    public class ProduceXMl {

    /**
     * |-『统战部』
    40      |-『干部科』
    41      |-『秘书科』
    42      |-『区民族宗教局』
    43          |-『民族宗教科』
    44          |-『佛教协会』
    45      |-『联络科』
    46  |-『台湾事务办公室』
    47      |-『办公室』
    48      |-『台胞接待站』  */



    public static void main(String[] args) throws IOException {
    Document doc = new Document();
    Element root = new Element("根");
    doc.setRootElement(root);

    Element tongzhanbu = new Element("统战部");
    root.addContent(tongzhanbu);

    tongzhanbu.addContent(new Element("干部科").setText("干部"));
    tongzhanbu.addContent(new Element("秘书科").setText("秘书"));

    Element zhongjiao = new Element("区民族宗教局");
    tongzhanbu.addContent(zhongjiao);
    zhongjiao.addContent(new Element("民族宗教科").setText("民族宗教"));
    zhongjiao.addContent(new Element("佛教协会").setText("佛教协会"));

    tongzhanbu.addContent(new Element("联络科").setText("联络"));
     
    Element taiban  = new Element("台湾事务办公室");
    root.addContent(taiban);
    taiban.addContent(new Element("办公室").setText("办公室"));
    taiban.addContent(new Element("台胞接待站").setText("台胞接待站"));


    XMLOutputter outp = new XMLOutputter();

    Format format=Format.getPrettyFormat();
    format.setEncoding("GBK");
    outp.setFormat(format);
    outp.output(doc,System.out);

    }
    }
      

  4.   

    运行结果:
    <?xml version="1.0" encoding="GBK"?>
    <根>
      <统战部>
        <干部科>干部</干部科>
        <秘书科>秘书</秘书科>
        <区民族宗教局>
          <民族宗教科>民族宗教</民族宗教科>
          <佛教协会>佛教协会</佛教协会>
        </区民族宗教局>
        <联络科>联络</联络科>
      </统战部>
      <台湾事务办公室>
        <办公室>办公室</办公室>
        <台胞接待站>台胞接待站</台胞接待站>
      </台湾事务办公室>
    </根>
      

  5.   

    我不知道对xml的理解是否正确,但编写思路是这样的 用jdom在www.jdom.org下载