• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
学习笔记
Misaka的学习笔记
博客园    首页    新随笔    联系   管理    订阅  订阅
c#读取和写入XML文件帮助类

一,代码

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;
        }
    }
}

 

posted on 2023-11-09 11:41  我们打工人  阅读(92)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3