LINQ體驗(二)LINQ to XML

Linq to xml操作XML

LINQ to XML提供了更方便的讀寫xml方式。前幾篇文章的評論中總有朋友提,你爲啥不用linq to xml?現在到時候了,linq to xml出場了。

.Net中的System.Xml.Linq命名空間提供了linq to xml的支持。這個命名空間中的XDocument,XElement以及XText,XAttribute提供了讀寫xml文檔的關鍵方法。

1. 使用linq to xml寫xml:

使用XDocument的構造函數可以構造一個Xml文檔對象;使用XElement對象可以構造一個xml節點元素,使用XAttribute構造函數可以構造元素的屬性;使用XText構造函數可以構造節點內的文本。

如下實例代碼:

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. var xDoc = new XDocument(new XElement( "root",
  6. new XElement("dog",
  7. new XText("dog said black is a beautify color"),
  8. new XAttribute("color", "black")),
  9. new XElement("cat"),
  10. new XElement("pig", "pig is great")));
  11. //xDoc輸出xml的encoding是系統默認編碼,對於簡體中文操作系統是gb2312
  12. //默認是縮進格式化的xml,而無須格式化設置
  13. xDoc.Save(Console.Out);
  14. Console.Read();
  15. }
  16. }

上面代碼將輸出如下Xml:

  1. <?xml version="1.0" encoding="gb2312"?>
  2. <root>
  3. <dog color="black">dog said black is a beautify color</dog>
  4. <cat />
  5. <pig>pig is great</pig>
  6. </root>

可以看出linq to xml比XmlDocument和XmlWriter要方便很多。

2. 使用linq to xml 讀取xml

Linq是從集合中查詢對象,在linq to xml中的集合是通過XElement的Elements(),Elements(string name),以及Descendants、DescendantsAndSelf、Ancestors、AncestorsAndSelf的幾個重載方法中獲得。

獲得XElement集合之後,可以通過XElement的Attribute(string name)方法獲得元素的屬性值,可以通過XElement的Value屬性獲得節點的文本值;使用linq就可以方便的做查詢,做篩選排序了

還是上例中的xml,我們要讀取root的所有字節點,並打印出來,如下代碼:

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. var xDoc = new XDocument(new XElement( "root",
  6. new XElement("dog",
  7. new XText("dog said black is a beautify color"),
  8. new XAttribute("color", "black")),
  9. new XElement("cat"),
  10. new XElement("pig", "pig is great")));
  11. //xDoc輸出xml的encoding是系統默認編碼,對於簡體中文操作系統是gb2312
  12. //默認是縮進格式化的xml,而無須格式化設置
  13. xDoc.Save(Console.Out);
  14. Console.WriteLine();
  15. var query = from item in xDoc.Element( "root").Elements()
  16. select new
  17. {
  18. TypeName = item.Name,
  19. Saying = item.Value,
  20. Color = item.Attribute("color") == null?(string)null:item.Attribute("color").Value
  21. };
  22. foreach (var item in query)
  23. {
  24. Console.WriteLine("{0} 's color is {1},{0} said {2}",item.TypeName,item.Color??"Unknown",item.Saying??"nothing");
  25. }
  26. Console.Read();
  27. }
  28. }

3. Linq to xml簡單的應用

應用需求: 讀取博客園的rss,然後在頁面上輸出最新的10篇博客信息

實現要點: 通過XDocument的Load靜態方法載入Xml,通過linq查詢最新10條數據

代碼如下:

  1. <%@ Page Language="C#" AutoEventWireup="true" %>
  2. <script runat="server">
  3. protected override void OnLoad(EventArgs e)
  4. {
  5. //實際應用,通過讀取博客園的RSS生成Html代碼顯示最新的博客列表
  6. //使用XDocument的Load靜態方法載入Xml
  7. //玉開技術博客 http://www.cnblogs.com/yukaizhao
  8. var rssXDoc = XDocument.Load("http://www.cnblogs.com/rss");
  9. //使用linq to xml查詢前10條新博客
  10. var queryBlogs = (from blog in rssXDoc.Descendants("item")
  11. select new
  12. {
  13. Title = blog.Element("title").Value,
  14. Url = blog.Element("link").Value,
  15. PostTime = DateTime.Parse(blog.Element("pubDate").Value)
  16. }).Take(20);
  17. repeaterBlogs.DataSource = queryBlogs;
  18. repeaterBlogs.DataBind();
  19. base.OnLoad(e);
  20. }
  21. </script>
  22. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  23. <html xmlns="http://www.w3.org/1999/xhtml">
  24. <head runat="server">
  25. <title>Linq to Xml 實例</title>
  26. </head>
  27. <body>
  28. <ol>
  29. <asp:Repeater ID="repeaterBlogs" EnableViewState="false" runat="server">
  30. <ItemTemplate>
  31. <li><span style="float: right">
  32. <%#Eval("PostTime") %></span><a href="<%#Eval("Url") %>"><%#Eval("Title") %></a></li>
  33. </ItemTemplate>
  34. </asp:Repeater>
  35. </ol>
  36. </body>
  37. </html>

C#的發展讓讀寫Xml越來越簡單了。

編者注:

本來想轉一篇更全面的博文,但苦於該文篇幅太大,而且包含很多圖片,只好作罷。特把鏈接粘過來以饗博友:http://www.cnblogs.com/luckdv/articles/1728088.html?login=1

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章