下面是一个读取XML文档的比较通用的方法,可以很方便地读取XML文档格式.XML文档如下:




















读取该文档的C#代码如下所示:
/// <summary>
/// 获取XML文档中元素的值
/// </summary>
/// <param name="parentNodePath">父级节点位置,如RolesRoot/Roles</param>
/// <param name="childNodeName">子节点名称,如要在Role节点下找相关元素值</param>
/// <param name="matchElementName">要进行匹配的元素名称,如通过ID元素值来找匹配</param>
/// <param name="id">ID元素值</param>
/// <param name="elementName">需要获取的元素名称</param>
/// <returns></returns>
public static string GetXmlElementValue(string parentNodePath, string childNodeName,string matchElementName, string id, string elementName)
{
string outPut = string.Empty;
try
{
string xmlpath = ConfigurationManager.AppSettings["RolesConfig"];
XmlDocument doc = new XmlDocument();
doc.Load(xmlpath);
XmlNodeList nodes = doc.SelectSingleNode(parentNodePath).ChildNodes;
foreach (XmlElement node in nodes)
{
if (node.Name == childNodeName)
{
if (node.Attributes[matchElementName].Value == id)
{
outPut = node.Attributes[elementName].Value;
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
return outPut;
}
上面介绍了读取一般格式的XML文档的方法,下面介绍读取特殊XML文件属性的方法,该XML文档定义了ID属性,如下:

























我们通过ID属性读取该XML文档,获取元素的值.
/// <summary>
/// 通过ID获取元素值
/// </summary>
/// <param name="id">XML文档中定义的唯一ID属性</param>
/// <param name="elementName">对应ID元素下要查找的元素名称</param>
/// <returns></returns>
public static string GetXmlElementValueById(string id, string elementName)
{
string outPut = string.Empty;
try
{
string xmlpath = ConfigurationManager.AppSettings["RolesConfig"];
XmlDocument doc = new XmlDocument();
doc.Load(xmlpath);
XmlElement elem = doc.GetElementById(id);
outPut = elem.Attributes[elementName].Value;
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
return outPut;
}