标签:
配置文件
<?xml>
<root>
<parent name="C">
<child name="C1">Spring</child>
<child name="C2">Summer</child>
</parent>
<parent name="D">
<child name="D1">autome</child>
<child name="D2">winter</child>
</parent>
</root>
调用方法
var XmlLevel2Helper=new XmlLevel2Helper("parent","child");
var value=XmlLevel2Helper.GetNodeValue("D","D2")
public class XmlLevel2Helper
{
private readonly String _parentNodeName = "Controller";
private readonly String _childNodeName = "Action";
public XmlLevel2Helper()
{
}
public XmlLevel2Helper(String parentNodeName, String childNodeName)
{
_parentNodeName = parentNodeName;
_childNodeName = childNodeName;
}
/// <summary>
/// 读取 2层Xml文件Node的值.
/// </summary>
/// <param name="filePath">如~/Config/CustomConfig.xml</param>
/// <param name="pNode">第一层Node名</param>
/// <param name="cNode">第二层Node名</param>
/// <returns></returns>
public string GetNodeValue(String filePath,string pNode, string cNode)
{
XElement rootElement = XElement.Load(HttpContext.Current.Server
.MapPath(filePath));
XElement pElement = FindElementByAttribute(rootElement, _parentNodeName, cNode);
if (pElement != null)
{
XElement cElement = FindElementByAttribute(pElement, _childNodeName, pNode);
if (cElement != null)
{
return cElement.Value;
}
}
return "";
}
/// <summary>
/// 根据Attribute找到相应的子元素
/// </summary>
/// <param name="xElement"></param>
/// <param name="tagName"></param>
/// <param name="attribute"></param>
/// <returns></returns>
private XElement FindElementByAttribute(XElement xElement, string tagName, string attribute)
{
return xElement.Elements(tagName).FirstOrDefault
(x => x.Attribute("name").Value.Equals(attribute, StringComparison.OrdinalIgnoreCase));
}
}
标签:
原文地址:http://www.cnblogs.com/zhshlimi/p/5457363.html