標籤:
總結一下c#操作xml,之前用的比較多,都是直接資料庫的操作xml,今天查看了一些資料,發現c#操作xml也是很方便,有一些方面給sql直接操作xml 更加方便,如增加一些動態節點,屬性。
先貼一些方法:
1 //所需要添加的命名空間 2 using System.Xml; 3 //初始化一個xml執行個體 4 XmlDocument xml=new XmlDocument(); 5 //匯入指定xml檔案 6 xml.Load(“xml檔案路徑path”); 7 //指定一個節點 8 XmlNode root=xml.SelectSingleNode("節點名稱"); 9 //擷取節點下所有直接子節點10 XmlNodeList childlist=root.ChildNodes;11 //判斷該節點下是否有子節點12 root.HasChildNodes;13 //擷取同名同級節點集合14 XmlNodeList nodelist=xml.SelectNodes("節點名稱");15 //產生一個新節點16 XmlElement node=xml.CreateElement("節點名稱");17 //將節點加到指定節點下,作為其子節點18 root.AppendChild(node);19 //將節點加到指定節點下某個子節點前20 root.InsertBefore(node,root.ChildeNodes[i]);21 //為指定節點的建立屬性並賦值22 node.SetAttribute("id","11111");23 //為指定節點添加子節點24 root.AppendChild(node);25 //擷取指定節點的指定屬性值26 string id=node.Attributes["id"].Value;27 //擷取指定節點中的文本28 string content=node.InnerText;29 //儲存XML檔案30 xml.Save(“xml檔案儲存體的路徑path”);View Code
再貼一些簡單的操作xml
1 XmlDocument xmlDo = new XmlDocument();2 xmlDo.LoadXml(xml);3 4 XmlNode xmlnode = xmlDo.SelectSingleNode("DimensionalCate//dimensional//field["+num+"]");5 XmlElement xe = (XmlElement)xmlnode;6 string label_value = xe.GetAttribute("label"); //擷取節點屬性名稱View Code
c#操作xml