这里介绍两种读取配置文件(.xml)的方法:XmlDocument及Linq to xml
首先简单创建一个配置文件:
<?xml version="1.0" encoding="utf-8" ?>
<Country Name="CHINA">
<Provinces>
<province Name="LN" Title="LiaoNing"></province>
<province Name="HB" Title="HeBei"></province>
<province Name="HLJ" Title="HeiLongJiang"></province>
</Provinces>
</Country>
我们所要做的是获取province节点的Name及Title属性的value
1、XmlDocument
public static void ReadByXmlDocument(string xmlPath)
{
XmlDocument doc = new XmlDocument();
doc.Load(xmlPath);
XmlNodeList provinceNodes = doc.SelectNodes("Country/Provinces/province");
if (provinceNodes.Count > )
{
foreach (XmlNode pNode in provinceNodes)
{
string name = pNode.Attributes["Name"].Value;
string title = pNode.Attributes["Title"].Value;
}
}
}
2、XElement
Note:XElement.Descendants(XName,name)方法传入的XName是节点标签。
public static void ReadByElement(string xmlPath)
{
XElement xElement = XElement.Load(xmlPath);
var provinces = from p in xElement.Descendants("province")
select new
{
name = p.Attribute("Name").Value,
title = p.Attribute("Title").Value
};
foreach (var item in provinces)
{
string name = item.name;
string title = item.title;
}
}