创建窗体。保存按钮添加saveFileDialog工具,这样可以在保存的时候直接选择文件保存。
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.Xml;
namespace fruit
{
public partial class Form1 : Form
{
public XmlDocument doc;
public XmlElement root;
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
doc = new XmlDocument();
XmlDeclaration declare = doc.CreateXmlDeclaration("1.0", "utf-8", "yes");
doc.AppendChild(declare);
root = doc.CreateElement("水果列表");
doc.AppendChild(root);
XmlElement list = doc.CreateElement("水果");
XmlAttribute name = doc.CreateAttribute("名称");
name.Value = textBox1.Text;
list.Attributes.Append(name);
XmlElement prize = doc.CreateElement("价格");
XmlText prize1 = doc.CreateTextNode(textBox2.Text);
prize.AppendChild(prize1);
XmlElement num = doc.CreateElement("数量");
XmlText num1 = doc.CreateTextNode(textBox3.Text);
num.AppendChild(num1);
root.AppendChild(list);
list.AppendChild(prize);
list.AppendChild(num);
}
private void button3_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string fruit = saveFileDialog1.FileName;
doc.Save(fruit);
MessageBox.Show("保存成功");
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
}
}
}
}
保存信息。
实现效果