星期五, 5月 04, 2018

[LINQ] XML Query

學習 LINQ to XML 筆記,該篇是紀錄如何利用 Descendants() 和 Elements() 來搜尋 XML 檔案

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 _02_XMLQuery
{
    class Program
    {
        static void Main(string[] args)
        {
            Query_Descendants();
            // Query_Element();
        }

        static string
            employees = "Employees",
            employee = "Employee",
            name = "Name",
            salary = "Salary";

        static int limit = 48_000;

        private static void Query_Descendants()
        {
            var result = XDocument
                .Load(DataHelper.XMLPath)
                .Descendants(employee) // 重點
                .Where(w => (int)w.Element(salary) > limit)
                .OrderByDescending(o => (int)o.Element(salary))
                .Select(s => s.Element(name).Value)
                .ToList();

            ShowData(result);
        }

        private static void Query_Element()
        {
            var result = XDocument
                .Load(DataHelper.XMLPath)
                .Elements(employees) // 重點
                .Elements(employee) // 重點
                .Where(w => (int)w.Element(salary) > limit)
                .OrderByDescending(o => (int)o.Element(salary))
                .Select(s => s.Element(name).Value)
                .ToList();

            ShowData(result);
        }

        private static void ShowData(IEnumerable<string> datas)
        {
            foreach (string data in datas)
            {
                Console.WriteLine(data);
            }
        }
    }
}

Elements() 來取子系,要一層一層抓,Descendants() 可以直接抓指定子系

[LINQ] XML Query

沒有留言:

張貼留言