dom4j 生成XML文件
生成的文件内容和格式:
<?xml version="1.0" encoding="UTF-8"?><mail> <from>xxx@sohu.com</from> <subject>Mail subject</subject> <content>Mail content</content> <to>xxx@qq.com</to> <cc>xxx@qq.com</cc> <bcc></bcc> <reply></reply> <attachment_path></attachment_path></mail>
import java.io.FileOutputStream;import java.io.OutputStream;import org.dom4j.Document;import org.dom4j.DocumentHelper;import org.dom4j.Element;import org.dom4j.io.OutputFormat;import org.dom4j.io.XMLWriter;public class TestCreateXML{public static void main(String[] args){TestCreateXML test = new TestCreateXML();OutputStream os;try{os = new FileOutputStream("C:/mail_test.xml");// xml输出的格式OutputFormat format = new OutputFormat();format.setEncoding("UTF-8");format.setIndent(true);// 是否缩进format.setIndentSize(2);format.setNewlines(true);XMLWriter writer = new XMLWriter(os, format);writer.write(test.createSendContent());// 关闭资源writer.close();os.close();}catch (Exception e){e.printStackTrace();}}private Document createSendContent(){Document document = DocumentHelper.createDocument();document.setXMLEncoding("UTF-8");// 添加元素MailElement mailElement = document.addElement("mail");// 发件人Element form = mailElement.addElement("from");form.setText("xxx@sohu.com");// 主题Element subject = mailElement.addElement("subject");subject.setText("Mail subject");// 内容Element content = mailElement.addElement("content");content.setText("Mail content");// 收件人信息Element to = mailElement.addElement("to");to.setText("xxx@qq.com");// 抄送人的地址Element cc = mailElement.addElement("cc");cc.setText("xxx@qq.com");// 密送人的地址Element bcc = mailElement.addElement("bcc");bcc.setText("");// replyElement reply = mailElement.addElement("reply");reply.setText("");// 附件Element attachMentPath = mailElement.addElement("attachment_path");attachMentPath.setText("");return document;}}1 楼 xulonghui2011 2013-06-19 xstream 比较好 这个需要自己构建节点,有点麻烦