欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

dom4j 生成XML文件 博客分类: dom4j xml dom4j

程序员文章站 2024-02-25 23:57:33
...
生成的文件内容和格式:

<?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>


java代码:

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");			
		// 添加元素Mail
		Element 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("");
		// reply
		Element reply = mailElement.addElement("reply");
		reply.setText("");		
		// 附件
		Element attachMentPath = mailElement.addElement("attachment_path");
		attachMentPath.setText("");
		return document;

	}
	
}

相关标签: xml dom4j