星期一, 5月 07, 2018

[LINQ] XML Delete

學習 LINQ to XML 筆記,該篇是紀錄如何利用 Remove() 來移除 XML 檔案內的 Element

Employee Class
namespace Helper
{
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public bool Gender { get; set; }
        public int Salary { get; set; }
    }
}
DataHelper Class
namespace Helper
{
    public static class DataHelper
    {
        public static string XMLPath = @"D:\Temp\XMLDemo.xml";

        public static List<Employee> GetEmployees()
        {
            return new List<Employee>
            {
                new Employee {ID = 1, Name = "張三", Gender = false, Salary = 50000},
                new Employee {ID = 2, Name = "李四", Gender = true,  Salary = 45000},
                new Employee {ID = 3, Name = "王五", Gender = false, Salary = 65000},
                new Employee {ID = 4, Name = "丁六", Gender = true,  Salary = 28000}
            };
        }

        public static void XMLFileExist()
        {
            if (File.Exists(XMLPath) == false)
            {
                throw new FileNotFoundException(XMLPath);
            }
        }
    }
}

主程式
using Helper;
using System.Xml.Linq;

namespace _05_XMLDelete
{
    class Program
    {
        static void Main(string[] args)
        {
            Remove("3");
        }

        /// <summary>
        /// 刪除指定 Element
        /// </summary>
        private static void Remove(string ID)
        {
            XDocument xDoc = XDocument.Load(DataHelper.XMLPath);

            XElement xEle = xDoc.Descendants("Employee")
                .Where(w =>
                {
                    XAttribute xAttr = w.Attribute("ID");
                    return xAttr != null && xAttr.Value == ID;
                }).FirstOrDefault();

            if (xEle != null)
            {
                xEle.Remove();
            }

            xDoc.Save(DataHelper.XMLPath);
        }
    }
}
[LINQ] XML Delete

沒有留言:

張貼留言