linqtoxml如何操作XML

這篇文章將為大家詳細講解有關(guān)linq to xml如何操作XML,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

公司主營業(yè)務:成都做網(wǎng)站、成都網(wǎng)站建設、移動網(wǎng)站開發(fā)等業(yè)務。幫助企業(yè)客戶真正實現(xiàn)互聯(lián)網(wǎng)宣傳,提高企業(yè)的競爭能力。成都創(chuàng)新互聯(lián)公司是一支青春激揚、勤奮敬業(yè)、活力青春激揚、勤奮敬業(yè)、活力澎湃、和諧高效的團隊。公司秉承以“開放、自由、嚴謹、自律”為核心的企業(yè)文化,感謝他們對我們的高要求,感謝他們從不同領域給我們帶來的挑戰(zhàn),讓我們激情的團隊有機會用頭腦與智慧不斷的給客戶帶來驚喜。成都創(chuàng)新互聯(lián)公司推出麻城免費做網(wǎng)站回饋大家。

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

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

1. 使用linq to xml寫xml:

使用XDocument的構(gòu)造函數(shù)可以構(gòu)造一個Xml文檔對象;使用XElement對象可以構(gòu)造一個xml節(jié)點元素,使用XAttribute構(gòu)造函數(shù)可以構(gòu)造元素的屬性;使用XText構(gòu)造函數(shù)可以構(gòu)造節(jié)點內(nèi)的文本。

如下實例代碼:

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輸出xml的encoding是系統(tǒng)默認編碼,對于簡體中文操作系統(tǒng)是gb2312
        //默認是縮進格式化的xml,而無須格式化設置
        xDoc.Save(Console.Out);

        Console.Read();
    }
}

上面代碼將輸出如下Xml:

<?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>

可以看出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屬性獲得節(jié)點的文本值;使用linq就可以方便的做查詢,做篩選排序了

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

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輸出xml的encoding是系統(tǒng)默認編碼,對于簡體中文操作系統(tǒng)是gb2312
        //默認是縮進格式化的xml,而無須格式化設置
        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();
    }
}

3. Linq to xml簡單的應用

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

實現(xiàn)要點: 通過XDocument的Load靜態(tài)方法載入Xml,通過linq查詢最新10條數(shù)據(jù)

代碼如下:

<%@ Page Language="C#" AutoEventWireup="true" %>
<script runat="server">
    protected override void OnLoad(EventArgs e)
    {
        //實際應用,通過讀取博客園的RSS生成Html代碼顯示最新的博客列表
        //使用XDocument的Load靜態(tài)方法載入Xml
        //玉開技術(shù)博客 http://www.php.cn/
        var rssXDoc = XDocument.Load("http://www.cnblogs.com/rss");

        //使用linq to xml查詢前10條新博客
        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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://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>

關(guān)于“l(fā)inq to xml如何操作XML”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

網(wǎng)站欄目:linqtoxml如何操作XML
網(wǎng)站路徑:http://muchs.cn/article26/pishjg.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供響應式網(wǎng)站、虛擬主機云服務器、網(wǎng)站改版、用戶體驗

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站建設網(wǎng)站維護公司