dom4j 生成XML文件

生成的文件内容和格式:

<?xml version="1.0" encoding="UTF-8"?>

<mail>
  <from>[email protected]</from>
  <subject>Mail subject</subject>
  <content>Mail content</content>
  <to>[email protected]</to>
  <cc>[email protected]</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("[email protected]");
		// 主题
		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("[email protected]");
		// 抄送人的地址
		Element cc = mailElement.addElement("cc");
		cc.setText("[email protected]");
		// 密送人的地址
		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)