概述:
linq to xml(下面簡稱ltx好了),是微軟根據linq技術對于XML的CURD.使用起來比System.XML中的XML操作方式更加簡便.這段時間使用它在公司里升級了老板的郵件系統,頗有心得,現在總結一下.
主要對象:
1.XDocument:XML文檔對象,載入方式是根據其靜態方法載入XML文檔: XDocument xDoc = XDocument.load(@"**xml路徑**")
.Element("NodeName") 獲得子節點XElement對象,XDoc下一般是根節點
.Sava("xmlpath") 保存文檔到xml文件
XElement xele = xdocTypeDef.Element("root").Elements().Where(p => p.Attribute("Name").Value == strTopName).Single();
2.XElement:節點對象
.Element("NodeName") 獲得子節點XElement對象
.Elements() 返回子節點集合
.Elements("NodeName")返回名字是"NodeName"的子節點集合
.Add(param[] obj) 增加的可以是多個節點或是屬性
.Remove() 將節點刪除.
.value 節點屬性
3.XAttribute:屬性對象
知道這些就可以在結合linq就可以對XML進行操作了.
下面是最近的小項目中為節點增加子節點和屬性的部分源碼:
1 public static bool addElement(XElement xeleNode,string addEleType, string strContralName,string strContent) 2 { 3 XElement xeleChild = new XElement(addEleType); 4 xeleChild.Add(new XAttribute(strContralName,strContent)); 5 //判斷有木有此子控件 6 if ( xeleNode.Elements().Count() > 0 && xeleNode.Elements().Where(p => p.Attribute(strContralName).Value == strContent).Count() > 0) 7 return false; 8 xeleNode.Add(xeleChild); 9 10 return true;11 12 }13 14 public static bool addAttr(XElement xeleNode, Dictionary<string, string> dic)15 {16 bool flag = true;17 foreach (KeyValuePair<string, string> pair in dic)18 {19 if (xeleNode.Elements().Where(p => p.Attribute("Name").Value == pair.Key).Count() > 0)20 {21 flag = false;22 continue;23 }24 XElement xeleChild = new XElement("Attribute");25 xeleChild.Add(new XAttribute("Name",pair.Key.ToString()));26 xeleChild.Value = pair.Value.ToString();27 xeleNode.Add(xeleChild);28 }29 return flag;30 }View Code
刪除和修改節點
...//修改節點 XElement xele = XEleFirstNode.Elements().Where(p => p.Attribute("Name").Value == strContralName ).Single() as XElement; xele = xele.Elements().Where(p => p.Attribute("Name").Value == strAttr).Single() as XElement; xele.Value = strAttrDes; xDoc.Save(strPath);...//del nodeif (MessageBox.Show("確定刪除?", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No) return; foreach(object str in lBAtrributes.SelectedItems) //listbox mutiselect { string strAttr = str.ToString(); XElement xeleAttr = XEleSecondNode.Elements().Where(p => p.Attribute("Name").Value == strAttr).Single() as XElement; xeleAttr.Remove(); } xDoc.Save(strPath);
多多練習方能掌握.
新聞熱點
疑難解答