码迷,mamicode.com
首页 > 其他好文 > 详细

2层Xml读取类

时间:2016-05-04 10:17:34      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

配置文件

<?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));
}
}

2层Xml读取类

标签:

原文地址:http://www.cnblogs.com/zhshlimi/p/5457363.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!