在讀取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); }