在JSON沒流行起來的時候xml一直作為程序存儲配置信息的主流介質;特別是小型數據表方面還是不錯的選擇,所以經常涉及到的操作無非也就是增刪改查,這篇博客主要是對這些對比較常用的操作做了個簡單的總結
文件加載
SelectNodes()、SelectSingleNode()節點獲取大法
創建XML文檔及設置元素值
XmlReader與XmlWriter
DataSet與XML數據
Linq to XML
XML序列化與反序列化
XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(fileName);//文件路徑或者URL地址 Console.WriteLine(xmlDoc.InnerXml); Console.WriteLine("==============有逼格的分割線================"); xmlDoc.Load("http://feed.cnblogs.com/blog/picked/rss");//博客園精華帖RSS Console.WriteLine(xmlDoc.InnerXml);
using (FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(stream); Console.WriteLine(xmlDoc.InnerXml); }
Load()方法還重載了一些方法,並且還有別的方式可以加載XML文檔,比如LoadXml()直接加載一段XML串
XmlNodeList xmlNodes = xmlDoc.SelectNodes("/Names/Name");//第一個斜槓必須是根節點 foreach (XmlNode item in xmlNodes) { Console.WriteLine(item.InnerXml); } Console.WriteLine("=================================="); XmlNode xmlNode = xmlDoc.SelectSingleNode("/Names/Name"); Console.WriteLine(xmlNode.InnerXml); Console.WriteLine(xmlNode["LastName"].InnerText);//獲取子節點
<Root> <Item Id="1" Grade="1">張三</Item> <Item Id="2" Grade="1">李四</Item> <Item Id="3" Grade="2">王五</Item> <Item Id="4" Grade="3">趙六</Item> </Root>
XmlNodeList xmlNodes = xmlDoc.SelectNodes("/Root/Item[@Grade='1']");//XPath表達式獲取設置要獲取節點的特性值信息 foreach (XmlNode item in xmlNodes) { Console.WriteLine(item.InnerText); }
XmlNode xmlNode = xmlDoc.SelectSingleNode("/Root/Item[position()=3]");//獲取第N個節點(根據XML節點的順序) Console.WriteLine(xmlNode.InnerText); Console.WriteLine("=============================="); XmlNodeList xmlNodes = xmlDoc.SelectNodes("/Root/Item[position()<=3]");//獲取從第一個到第N個的節點(根據XML節點的順序 foreach (XmlNode item in xmlNodes) { Console.WriteLine(item.InnerText); } Console.WriteLine("=============================="); xmlNodes = xmlDoc.SelectNodes("/Root/Item[position() > 2]");//獲取大於第N個的節點(根據XML節點的順序) foreach (XmlNode item in xmlNodes) { Console.WriteLine(item.InnerText); }
XmlDocument xmlDoc = new XmlDocument(); XmlNode rootNode = xmlDoc.CreateElement("Root");//創建一個節點 xmlDoc.AppendChild(rootNode); Console.WriteLine(xmlDoc.InnerXml); Console.WriteLine("==============有逼格的分割線================"); XmlNode node = xmlDoc.CreateElement("Item"); XmlAttribute attribute = xmlDoc.CreateAttribute("Id");//創建節點特性 attribute.Value = "1";//設置特性值 node.Attributes.Append(attribute); node.InnerText = "張三"; rootNode.AppendChild(node); Console.WriteLine(xmlDoc.InnerXml); Console.WriteLine("==============有逼格的分割線================"); node = xmlDoc.CreateElement("Item"); attribute = xmlDoc.CreateAttribute("Id"); attribute.Value = "2"; node.Attributes.Append(attribute); node.InnerText = "李四"; rootNode.AppendChild(node); Console.WriteLine(xmlDoc.InnerXml);
xmlDoc.Save(fileName);//保存到文件
XmlReader操作XML比XmlDocument更快、內存消耗更少(可以寫一個測試驗證一下);但是它需要去手動判斷元素的類型,操作起來比XmlDocument稍微蛋疼一些
using (XmlWriter xmlWriter = XmlWriter.Create(fileName)) { xmlWriter.WriteStartDocument();//開始寫入xml文檔 xmlWriter.WriteStartElement("users"); xmlWriter.WriteStartElement("user"); xmlWriter.WriteAttributeString("Id", "42"); xmlWriter.WriteString("張三"); xmlWriter.WriteEndElement(); xmlWriter.WriteStartElement("user"); xmlWriter.WriteAttributeString("Id", "39"); xmlWriter.WriteString("李四"); xmlWriter.WriteEndDocument();//結束寫入xml文檔 } using (XmlReader xmlReader = XmlReader.Create(fileName)) { while (xmlReader.Read()) { if (xmlReader.NodeType == XmlNodeType.Element)//元素的類型 { Console.WriteLine(xmlReader.Name);//元素名稱 if (xmlReader.HasAttributes) { Console.WriteLine(xmlReader.GetAttribute("Id"));//元素名稱 } Console.WriteLine(xmlReader.ReadOuterXml());//獲取節點的所有子內容 } } }
通過XmlReader將數據讀入到DataSet數據集中
using (XmlReader xmlReader = XmlReader.Create(fileName, new XmlReaderSettings())) { DataSet ds = new DataSet(); ds.ReadXml(xmlReader); DataTable dt = ds.Tables[0]; for (int i = 0; i < dt.Rows.Count - 1; i++) { object[] items = dt.Rows[i].ItemArray; Console.WriteLine(string.Join(" ", items)); } }
將數據表保存到XML文件也是比較常用的
DataSet ds = new DataSet(); DataTable dt = new DataTable(); dt.Columns.Add(new DataColumn("Id", Type.GetType("System.Int32"))); dt.Columns.Add(new DataColumn("Grade", Type.GetType("System.Int32"))); dt.Columns.Add(new DataColumn("Name", Type.GetType("System.String"))); DataRow dr = dt.NewRow(); dr["Id"] = 9999; dr["Grade"] = 3; dr["Name"] = "孫七"; dt.Rows.Add(dr); ds.Tables.Add(dt); ds.Tables[0].TableName = "Student";//每張表為根節點下的第一個子節點 ds.WriteXml(fileName);
通過linq操作XML上手快、操作方便
//查詢 XDocument xdoc = XDocument.Load(fileName); var query = from item in xdoc.Descendants("Item") select new { Id = item.Attribute("Id").Value, Name = item.Value }; foreach (var item in query) { Console.WriteLine(item.Id + " " + item.Name); }
//添加 XDocument xdoc = XDocument.Load(fileName); XElement xele = new XElement("Item","吳十?");//創建節點 xele.SetAttributeValue("Id", 10);//設置節點特性值 xdoc.Element("Root").Add(xele); xdoc.Save(fileName);
//刪除 XDocument xdoc = XDocument.Load(fileName); XElement xele = xdoc.Descendants("Item").Where(c => c.Attribute("Id").Value.Equals("10")).FirstOrDefault(); xele.Remove(); xdoc.Save(fileName);
//修改 XDocument xdoc = XDocument.Load(fileName); XElement xele = xdoc.Descendants("Item").Where(c => c.Attribute("Id").Value.Equals("1")).FirstOrDefault(); xele.Value = "流年"; xdoc.Save(fileName);
//序列化 var student = new Student() { Id = 1, Grade = 2, Name = "王五" }; XmlSerializer serializer = new XmlSerializer(typeof(Student)); serializer.Serialize(Console.Out, student);
//反序列化 string input = "<?xml version=\"1.0\" encoding=\"gb2312\"?><student><Id> 1 </Id><Grade> 2 </Grade><Name> 李四 </Name></student>"; using (StringReader sr = new StringReader(input)) { XmlSerializer serializer = new XmlSerializer(typeof(Student)); Student student = (Student)serializer.Deserialize(sr); Console.WriteLine(student.Name); }
http://www.dotnetcurry.com/linq/564/linq-to-xml-tutorials-examples
http://www.tutorialspoint.com/linq/linq_xml.htm
https://msdn.microsoft.com/en-us/library/mt693062.aspx
http://broadcast.oreilly.com/2010/10/understanding-c-simple-linq-to.html
http://www.codeproject.com/Articles/24376/LINQ-to-XML
http://csharp.net-tutorials.com/xml/reading-xml-with-the-xmlreader-class/
https://msdn.microsoft.com/zh-cn/library/58a18dwa(v=vs.120).aspx
http://csharp.net-informations.com/xml/xml-de-serialization.htm