简体   繁体   English

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

[英]get the value of an element that is nested within an element linq to xml

I have an RSS xml that I am trying to extract info from and I have been using code that extracts the value from the element just fine. 我有一个RSS xml,我试图从中提取信息,我一直在使用从元素中提取值的代码。 But now I have a problem that I have an element nested within another element which I can't figure out how to extract the information from. 但现在我有一个问题,我有一个嵌套在另一个元素中的元素,我无法弄清楚如何从中提取信息。

Here is my xml structure that I'm using. 这是我正在使用的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>

I need to get the <url> element within the <image> element for a specific <item> So I have been using this code to get the other elements 我需要在<image>元素中获取特定<item><url>元素所以我一直在使用此代码来获取其他元素

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,
           };

Please help me to get the value of the image url node. 请帮我获取图片网址节点的值。

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")
           };

If image element cab be missing, then you should check it before getting url: 如果缺少image元素cab,那么你应该在获取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")
           };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM