簡體   English   中英

無法將C#xml中的xml讀取到linq

[英]not able to read xml in C# xml to linq

您好,我正在嘗試讀取xml文件,但我無法在此處獲取要素,這是我的示例代碼

<?xml version="1.0" encoding="utf-8"?>
    <feed xmlns="http://www.w3.org/2005/Atom">
        <title>Read xml file</title>
        <link href=""></link>
        <updated>2014-01-06T10:32:04.230060</updated>
        <author><name>rss</name></author>

        <entry>
            <title>abc: Watching &#34;Mary Tyler Moore.&#34; Every character is drinking Scotch. #The70s </title>
            <link href="http://RobertOSimonson/status/417858586618781697"></link>
            <id>/RobertOSimonson/status/417858586618781697</id>
            <updated>2013-12-30T19:23:00Z</updated>
            <published>2013-12-30T19:23:00Z</published>
            <summary>Watching &#34;Mary Tyler Moore.&#34; Every character is drinking Scotch. #The70s </summary>
        </entry>

        <entry>
            <title>abc: Galliano makes very appropriate cameo in the &#39;70s-set &#34;American Hustle.&#34; #AmericanHustle </title>
            <link href="http://RobertOSimonson/status/417511925258272768"></link>
            <id>/RobertOSimonson/status/417511925258272768</id>
            <updated>2013-12-29T20:26:00Z</updated>
            <published>2013-12-29T20:26:00Z</published>
            <summary>Galliano makes very appropriate cameo in the &#39;70s-set &#34;American Hustle.&#34; #AmericanHustle </summary>
        </entry>
</feed>

在我的C#代碼中,我正在嘗試這樣

var posts = (from p in rssFeed.Root.Elements("entry")
             select new
             {
                 Title = p.Element("title").Value,
                 Link = p.Element("link").Value,
             }).ToList();

foreach (var post in posts)
{
    Response.Write(post.Title + "<br>");
}

請提出我在做什么錯。 我想看里面的東西謝謝

您需要在查詢中包括xml名稱空間:

XNamespace ns = "http://www.w3.org/2005/Atom";
var posts = (from p in rssFeed.Root.Elements(ns + "entry")
             select new
             {
                 Title = p.Element(ns + "title").Value,
                 Link = p.Element(ns + "link").Value,
             }).ToList();

foreach (var post in posts)
{
    Console.WriteLine(post.Title);
}

在此處簽出C#的linq to xml示例: http : //msdn.microsoft.com/en-us/library/bb397976.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM