c#读取和写入XML文件帮助类

发布时间 2023-11-09 11:50:22作者: 三流程序媛

一,代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;

namespace Common.share.Helper
{
    public static class XmlHelper
    {
        public static int ReadXmlObject<T>(string filePath,string rootName, ref List<T> values) where T : new()
        {
            IList<T> list = new List<T>();
            if (File.Exists(filePath))
            {
                XDocument document = XDocument.Load(filePath);
                XElement root = document.Root;

if (root == null||root.Name!=rootName)
{
return 0;
}

                List<XElement> enumerable = root.Elements().ToList();
                var type = typeof(T);
                PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                foreach (XElement item in enumerable)
                {
                    T _t = Activator.CreateInstance<T>();
                    foreach (var property in properties)
                    {
                        var value = item.Element(property.Name).Value;
                        property.SetValue(_t, value, null);
                    }
                    list.Add(_t);
                    values = list.ToList();
                }
                return list.Count;
            }
            else
            {
                return 0;
            }
        }

        public static int SaveXmlObject<T>(string filePath,string rootName, IList<T> values) where T : class
        {
            XElement root = new XElement(rootName);
            Type type = typeof(T);
            string typeName = typeof(T).Name;
            var properties = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            foreach (var item in values)
            {
                //生成xml文档
                XElement Items = new XElement(typeName);
                foreach (var property in properties)
                {
                    var value = property.GetValue(item,null);
                    Items.SetElementValue(property.Name, value.ToString());
                }
                root.Add(Items);
            }
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            root.Save(filePath);
            return 1;
        }
    }
}