C# 读取XML数据
引用 System.Xml
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace Common
{
public class XMLHelper
{
public class XMLTitle
{
public string type { get; set; }
public string filename { get; set; }
}
public class XMLField
{
public string UserName { get; set; }
public string Sex { get; set; }
public string IDNumber { get; set; }
public string HireDate { get; set; }
public string PersonnelArea { get; set; }
public string JobTitle { get; set; }
public string SalaryDetail { get; set; }
public string Date { get; set; }
public string Address { get; set; }
public string Tel { get; set; }
}
/// <summary>
/// 获取XMl父节点下所有的子节点(当所有的子节点全部在总父节点下时)
/// </summary>
/// <param name="path">xml文件所在的路径</param>
/// <returns></returns>
public static Dictionary<XMLTitle, XMLField> GetXmlList(string path)
{
Dictionary<XMLTitle, XMLField> result = new Dictionary<XMLTitle, XMLField>();
var type = typeof(XMLField);
var propertyInfos = type.GetProperties();
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNodeList xmlNodeList = doc.SelectNodes("/configuration");
if (xmlNodeList != null)
{
foreach (XmlNode xmlNode1 in xmlNodeList)
{
foreach (XmlNode xmlNode2 in xmlNode1)
{
XMLTitle xMLTitle = new XMLTitle
{
type = xmlNode2.Attributes["type"].Value,
filename = xmlNode2.Attributes["filename"].Value,
};
XMLField xMLField = new XMLField();
foreach (XmlNode xmlNode3 in xmlNode2)
{
foreach (var propertyInfo in propertyInfos)
{
if (propertyInfo.Name.Equals(xmlNode3.Attributes["key"].Value))
{
propertyInfo.SetValue(xMLField, xmlNode3.Attributes["value"].Value, null);
}
}
}
result.Add(xMLTitle, xMLField);
}
}
}
return result;
}
}
}
XML文件内容
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<template type="" filename="">
<field key ="UserName" value="" />
<field key ="Sex" value="" />
<field key ="IDNumber" value="" />
<field key ="HireDate" value="" />
<field key ="PersonnelArea" value="" />
<field key ="JobTitle" value="" />
<field key ="SalaryDetail" value="" />
<field key ="Date" value="" />
<field key ="Address" value="" />
<field key ="Tel" value="" />
</template>
</configuration>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?