C#读取XML

        在读取XML中每次循环遍历xml好麻烦,弄一个linq查询的方法封装起来 方便,快捷,舒服

 

  不过最后一个xml的属性问题,总是想不到用什么更好的方法解决,各路大神求给意见

    

   /// <summary>

///获取xml指定节点的值

/// </summary>

/// <param name="path">xml路径</param>

/// <param name="xmlElement">节点名称</param>

/// <param name="xmlAttribute">节点属性</param>

/// <returns></returns>

private static string getXmlValue(string path, string xmlElement, params string[] xmlAttribute)

{

XDocument xmlDoc = XDocument.Load(path);

var results = from c in xmlDoc.Descendants(xmlElement)

select c;

string s = "";

if (xmlAttribute.Length == 0)

{

foreach (var item in results)

{

s = item.Value.ToString();

}

}

else

{

foreach (var item in results)

{

s = item.Attribute(xmlAttribute[0]).Value.ToString();

}

}

 

return s;

}

 

 

 

 

 

/// <summary>

///设置xml指定节点的值

/// </summary>

/// <param name="path">xml地址</param>

/// <param name="xmlName">xml节点名称</param>

/// <param name="xmlValue">要设置的值</param>

/// <param name="xmlAttribute">节点的属性</param>

private static void setXmlValue(string path, string xmlName, string xmlValue, params string[] xmlAttribute)

{

XDocument xmlDoc = XDocument.Load(path);

if (xmlAttribute.Length == 0)

{

xmlDoc.Element("root").Element(xmlName).SetValue(xmlValue);

}

else

{

xmlDoc.Element("root").Element(xmlName).Attribute(xmlAttribute[0]).SetValue(xmlValue);

}

 

xmlDoc.Save(path);

} 

 

posted @ 2014-12-01 16:29  若云  阅读(362)  评论(0编辑  收藏  举报