获取嵌套在元素linq中的元素的值到xml

时间:2014-05-24 13:01:33

标签: c# xml linq

我有一个RSS xml,我试图从中提取信息,我一直在使用从元素中提取值的代码。但是现在我有一个问题,我有一个嵌套在另一个元素中的元素,我无法弄清楚如何从中提取信息。

这是我正在使用的xml结构。

<item>
    <title>Nadal and Djokovic to lock horns again</title>
    <description>Rafael Nadal and Novak Djokovic will renew their rivalry in the Rome Masters final on Sunday</description>
    <link>http://www.espn.co.uk/tennis/sport/story/308417.html?CMP=OTC-RSS</link>
    <guid>http://www.espn.co.uk/tennis/sport/story/308417.html</guid>
    <pubDate>Sat, 17 May 2014 20:53:23 GMT</pubDate>
    <image>
        <url>www.espn.co.uk/PICTURES/CMS/66200/66275.2.jpg</url>
    </image>
</item>

我需要在<url>元素中获取<image>元素 对于特定的<item> 所以我一直在使用这段代码来获取其他元素

var info = from article in xmlDocument.Descendants("item")
           where article.Element("title").Value.Equals("Serena sets up Errani final in Rome")
           select new
           {
               title = article.Element("url").Value,
               description = article.Element("description").Value,
               link = article.Element("link").Value,
               pubDate = article.Element("pubDate").Value,
           };

请帮我获取图片网址的值。

1 个答案:

答案 0 :(得分:2)

string title = "Serena sets up Errani final in Rome";

var info = from i in xmlDocument.Descendants("item")
           where (string)i.Element("title") == title
           select new
           {
               title = title,
               description = (string)i.Element("description"),
               link = (string)i.Element("link"),
               pubDate = (string)i.Element("pubDate"),
               url = (string)i.Element("image").Element("url")
           };

如果image元素可能丢失,那么您应该在获取url之前检查它:

var info = from i in xmlDocument.Descendants("item")
           where (string)i.Element("title") == title
           let image = i.Element("image")
           select new
           {
               title = title,
               description = (string)i.Element("description"),
               link = (string)i.Element("link"),
               pubDate = (string)i.Element("pubDate"),
               url = image == null ? null : (string)image.Element("url")
           };