概述:
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進行操作了.
下面是最近的小項目中為節點增加子節點和屬性的部分源碼:
刪除和修改節點
... //修改節點 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 node if (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);
多多練習方能掌握.