C#保存XML文件

该博客介绍了如何在C#中创建一个窗体,添加保存按钮,并集成saveFileDialog工具。当点击保存按钮时,程序会生成一个XML文档,存储从文本框输入的水果名称、价格和数量信息,并允许用户选择保存文件的位置。点击保存后,信息会被成功写入文件,并清空文本框内容。
摘要由CSDN通过智能技术生成

 创建窗体。保存按钮添加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 = "";
            }
            
        }
    }
}

 保存信息。

 实现效果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值