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>