DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> XML學習教程 >> XML詳解
LINQ to XML 上手實作:用 C# 輕鬆讀寫 XML
編輯:XML詳解     

.NET 的 System.Xml.Linq 命名空間提供了 LINQ to XML 的支援。其中 XDocument、XElement、XText、XAttribute 這幾個類別,就是讀寫 XML 文件的關鍵角色。

一、用 LINQ to XML 產生 XML

寫 XML 的方式非常直覺:XDocument 的建構子用來組出整份文件,XElement 對應一個節點元素,XAttribute 負責元素的屬性,XText 則填入節點內的文字。因為元素可以嵌套建構子,整份文件往往一次就寫完。

class Program
{
    static void Main(string[] args)
    {
        var xDoc = new XDocument(
            new XElement("root",
                new XElement("dog",
                    new XText("dog said black is a beautify color"),
                    new XAttribute("color", "black")),
                new XElement("cat"),
                new XElement("pig", "pig is great")));

        // 輸出的 encoding 為系統預設編碼,簡體中文系統為 gb2312
        // 預設即為縮排格式化的 XML,不需額外設定
        xDoc.Save(Console.Out);

        Console.Read();
    }
}

執行後輸出:

<?xml version="1.0" encoding="gb2312"?>
<root>
  <dog color="black">dog said black is a beautify color</dog>
  <cat />
  <pig>pig is great</pig>
</root>

可以明顯看出,比起傳統的 XmlDocument 或 XmlWriter,LINQ to XML 的寫法乾淨了許多。

二、用 LINQ to XML 讀取 XML

LINQ 的本質是從集合中查詢物件。在 LINQ to XML 裡,集合來自 XElement 的幾個方法:Elements()、Elements(string name)、Descendants()、DescendantsAndSelf()、Ancestors()、AncestorsAndSelf()。

拿到 XElement 集合後,用 Attribute(string name) 取屬性值,用 Value 屬性取節點文字,接著就能用熟悉的 LINQ 語法做篩選與排序。

class Program
{
    static void Main(string[] args)
    {
        var xDoc = new XDocument(
            new XElement("root",
                new XElement("dog",
                    new XText("dog said black is a beautify color"),
                    new XAttribute("color", "black")),
                new XElement("cat"),
                new XElement("pig", "pig is great")));

        xDoc.Save(Console.Out);
        Console.WriteLine();

        var query = from item in xDoc.Element("root").Elements()
                    select new
                    {
                        TypeName = item.Name,
                        Saying   = item.Value,
                        Color    = item.Attribute("color") == null
                                   ? (string)null
                                   : item.Attribute("color").Value
                    };

        foreach (var item in query)
        {
            Console.WriteLine("{0}'s color is {1}, {0} said {2}",
                item.TypeName, item.Color ?? "Unknown", item.Saying ?? "nothing");
        }

        Console.Read();
    }
}

注意取值前一定要判空:Attribute() 找不到屬性時會回傳 null,cat 這種沒有 color 屬性的節點就會踩到,程式中已用 null 條件判斷與 ?? 運算子處理掉。

三、實戰應用:抓 RSS 顯示最新文章

需求很單純:讀取某個部落格的 RSS,在頁面上輸出最新的文章清單。實作要點是透過 XDocument 的靜態方法 Load() 直接載入遠端 XML,再用 LINQ 取出前幾筆。

<%@ Page Language="C#" AutoEventWireup="true" %>
<script runat="server">
    protected override void OnLoad(EventArgs e)
    {
        // 以 XDocument 的 Load 靜態方法載入遠端 XML
        var rssXDoc = XDocument.Load("https://www.cnblogs.com/rss");

        // 用 LINQ to XML 取出前 20 筆新文章
        var queryBlogs = (from blog in rssXDoc.Descendants("item")
                          select new
                          {
                              Title    = blog.Element("title").Value,
                              Url      = blog.Element("link").Value,
                              PostTime = DateTime.Parse(blog.Element("pubDate").Value)
                          }).Take(20);

        repeaterBlogs.DataSource = queryBlogs;
        repeaterBlogs.DataBind();
        base.OnLoad(e);
    }
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
    <title>LINQ to XML 實例</title>
</head>
<body>
    <ol>
        <asp:Repeater ID="repeaterBlogs" EnableViewState="false" runat="server">
            <ItemTemplate>
                <li>
                    <span style="float: right"><%# Eval("PostTime") %></span>
                    <a href="<%# Eval("Url") %>"><%# Eval("Title") %></a>
                </li>
            </ItemTemplate>
        </asp:Repeater>
    </ol>
</body>
</html>

結論很直接:C# 的演進,讓讀寫 XML 這件事越來越不需要動手寫一堆樣板程式。

來源:玉開的技術博客

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved