对XML的操作主要使用到的语法示例:
using System.Xml;
private static string XmlMarketingStaff = AppDomain.CurrentDomain.BaseDirectory + "config\\MarketingStaff.xml";
public static List<staffes> GetMarketingStaff2()
{XmlDocument xmlListDoc = XmlHlp.LoadXml(XmlMarketingStaff);
XmlNodeList nSys = null; nSys = xmlListDoc.SelectNodes("//staff"); List<QianjiaCRM2._0.Helper.StaffHlp.staffes> list = new List<QianjiaCRM2._0.Helper.StaffHlp.staffes>(nSys.Count); for (int i = 0; i < nSys.Count; i++) { XmlNode n = nSys[i]; QianjiaCRM2._0.Helper.StaffHlp.staffes c = new QianjiaCRM2._0.Helper.StaffHlp.staffes() { OldName = n.Attributes["name"].Value, Name = n.Attributes["name"].Value }; list.Add(c); } return list; }public static void UpdateTrailerXml(staffes sta)
{ XmlDocument xmlListDoc = XmlHlp.LoadXml(XmlMarketingStaff); XmlNodeList nSys = null; nSys = xmlListDoc.SelectNodes("//staff"); if (!string.IsNullOrEmpty(sta.OldName)) { for (int i = 0; i < nSys.Count; i++) { XmlNode n = nSys[i]; if (n.Attributes["name"].Value == sta.OldName) { n.Attributes["name"].Value = sta.Name; } } } else { XmlElement root = xmlListDoc.DocumentElement; XmlElement staff = xmlListDoc.CreateElement("staff"); staff.SetAttribute("name", sta.Name); root.AppendChild(staff); } xmlListDoc.Save(XmlMarketingStaff); }public static void Delete(string name)
{ XmlDocument xmlListDoc = XmlHlp.LoadXml(XmlMarketingStaff); XmlNodeList nSys = null; nSys = xmlListDoc.SelectNodes("//staff"); if (!string.IsNullOrEmpty(name)) { for (int i = 0; i < nSys.Count; i++) { XmlElement root = xmlListDoc.DocumentElement; XmlNode n = nSys[i]; if (n.Attributes["name"].Value == name) { root.RemoveChild(n); } } xmlListDoc.Save(XmlMarketingStaff); } }public class staffes
{ public string OldName { get; set; } public string Name { get; set; } }
/// <summary>
/// 加载Xml文件返回XmlDocument对象 /// </summary> /// <param name="xmlPath">文件路径</param> /// <returns></returns> public static XmlDocument LoadXml(string xmlPath) { XmlDocument xmlDoc = new XmlDocument(); XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreComments = true;//忽略文档里面的注释 XmlReader reader = XmlReader.Create(xmlPath, settings); xmlDoc.Load(reader); reader.Close(); return xmlDoc; }