c# xml文件增删改查

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

// 导入必要的命名空间
using System.Xml.Linq;
using System.IO;

namespace Xml文件操作
{
    class Program
    {
        //文件路径
        static string filepath = "recipes.xml";

        static void Main(string[] args)
        {

            for (int i = 0; i < 8; i++)
            {
                WriteXml(filepath, new Recipe() {ProductName="产品"+i.ToString(),Pressure = 100+i,Temperature = 25+i*10,Time = 60 });
            }
         

            var data = ReadXml(filepath);
            foreach (var item in data)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        
        }

        static void test()
        {
            Recipe obj = new Recipe();
            obj.ProductName = "三强";
            obj.Temperature = 78;
            obj.Pressure = 88;
            obj.Time = 45;

            WriteXml(filepath, obj);
        }
        /// <summary>
        /// 写入XML文件
        /// </summary>
        /// <param name="path"> 文件路径</param>
        /// <param name="obj">数据对象</param>
        static void WriteXml(string path ,Recipe obj)
        {
            try
            {
                XDocument doc;

                if (File.Exists(path))
                {
                    doc = XDocument.Load(path);
                }else
                {
                    //如果不存在,创建根节点
                    doc = new XDocument();
                    XElement root = new XElement("root");
                    doc.Add(root);
                }

                // 添加一个元素
                XElement element = new XElement("Recipe");
                //添加子元素
                element.Add(new XElement("ProductName", obj.ProductName));
                element.Add(new XElement("Temperature",obj.Temperature));
                element.Add(new XElement("Time", obj.Time));
                element.Add(new XElement("Pressure", obj.Pressure));

                doc.Root.Add(element);
                doc.Save(filepath);

    

            }
            catch (Exception) 
            {

                Console.WriteLine("Error writing to XML file");
            }

        }

        /// <summary>
        /// 读取文件,返回列表
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        static List<Recipe> ReadXml(string path)
        {
            List<Recipe> mylist = new List<Recipe>();
            if (File.Exists(path))
            {

                try
                {
                    //加载文件
                    XDocument doc = XDocument.Load(path);
                    //获取Recipe元素列表
                    var recipeElements = doc.Descendants("Recipe");
                    foreach (var item in recipeElements)
                    {
                        //实例化Recipe对象来接收数据
                        Recipe obj = new Recipe();
                        obj.ProductName = item.Element("ProductName").Value;
                        obj.Temperature = int.Parse(item.Element("Temperature").Value ?? "0");
                        obj.Pressure = int.Parse(item.Element("Pressure").Value ?? "0");
                        obj.Time = int.Parse(item.Element("Time").Value ?? "0");

                        // 添加到列表
                        mylist.Add(obj);
                    }

                }
                catch (Exception)
                {

                    Console.WriteLine("读取文件失败");
                }


            }else
            {
                Console.WriteLine("该文件不存在");
            }



            return mylist;
        }
        
        /// <summary>
        /// 修改文件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="productName"></param>
        /// <param name="recipe"></param>
        static void UpdaXml(string path,string productName,Recipe recipe)
        {
            if (File.Exists(path))
            {
                try
                {
                    XDocument doc = XDocument.Load(path);
                    var element = doc.Descendants("Recipe").FirstOrDefault(r => r.Element("ProductName")?.Value == productName);

                    if (element != null)
                    {
                        element.Element("Time").Value = recipe.Time.ToString();
                        element.Element("Temperature").Value = recipe.Temperature.ToString();
                        element.Element("Pressure").Value = recipe.Pressure.ToString();

                        doc.Save(path);

                    }

                }
                catch (Exception)
                {

                    Console.WriteLine($"Error updating recipe in XML file");
                }

            }else
            {
                Console.WriteLine("文件不存在");
            }
        }

        static void DelXml(string path,string productName)
        {
            if (File.Exists(path))
            {
                try
                {
                    XDocument doc = XDocument.Load(path);
                    var element = doc.Descendants("Recipe").FirstOrDefault(r => r.Element("ProductName")?.Value == productName);
                    if (element!=null)
                    {
                        element.Remove();
                        doc.Save(path);
                    }


                }
                catch (Exception)
                {

                    Console.WriteLine("删除文件失败");
                }

            }else
            {
                Console.WriteLine("文件不存在");
            }
        }
       
    }


    //定义一个数据类
    public class Recipe
    {
        public string ProductName { get; set; }
        public int Temperature { get; set; }
        public int Pressure { get; set; }
        public int Time { get; set; }

        public override string ToString()
        {
            return string.Format("{0,-30} {1,12} {2,12} {3,12}",
                $"ProductName:{ProductName}",
                $"Temperature:{Temperature}",
                $"Pressure:{Pressure}",
                $"Time:{Time}");
        }

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值