通过C#语言编写一个winform窗体输出xml文件
代码内容
C#代码部分
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WriteE_mail
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCantel_Click(object sender, EventArgs e)
{
Application.Exit();//退出程序
}
private void btnOK_Click(object sender, EventArgs e)
{
string path = "Note.xml";//用来存放文件的路径
FileStream fs = new FileStream(path,FileMode.Create);//创建文件流对象
StreamWriter sw = new StreamWriter(fs);//创建写入器
StringBuilder builder = new StringBuilder();//创建可变字符对象
builder.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");//追加行
builder.AppendLine("<Note>");
builder.AppendLine("<Day year=\"{0}\" month =\"{1}\" day =\"{2}\">");
builder.AppendLine("<To>{3}</To>");
builder.AppendLine("<From>{4}</From>");
builder.AppendLine("<Heading>{5}</Heading>");
builder.AppendLine("<Message>{6}</Message>");
builder.AppendLine("</Day>");
builder.AppendLine("</Note>");
string show = string.Format(builder.ToString(), txtYY.Text, txtMM.Text, txtDD.Text,txtTo.Text, txtFrom.Text, txtHeading.Text, txtMessage.Text );
sw.Write(show);//格式字符串
sw.Close();//关闭写入流
fs.Close();//关闭文件流
DialogResult result = MessageBox.Show("生成文件成功!","提示",MessageBoxButtons.OKCancel,MessageBoxIcon.Information);
if (result==DialogResult.OK)
{
this.Close();//关闭当前的窗体
}
}
}
}
窗体设计部分
最终效果
程序演示
生成的Note.xml
<?xml version="1.0" encoding="utf-8"?>
<Note>
<Day year="2016" month ="2" day ="23">
<To>赵三儿</To>
<From>李四儿</From>
<Heading>吃饭</Heading>
<Message>饭热好了,我知道你的身体不太好,要趁热吃</Message>
</Day>
</Note>