如何从xml文件中获取此值?

时间:2013-06-01 20:53:48

标签: c# xml linq-to-xml

这是xml:

 <item>
      <title>El Reno Tornado 5.31.13</title>
      <pubDate>Sat, 01 Jun 2013 14:01:12 -0400</pubDate>
      <link>http://url.com</link>
      <dc:creator>plankbone</dc:creator>
      <description>Chase video next to this monster tornado in El Reno Oklahoma. Check out the people driving on the wrong side of the road to escape it's path!</description>
      <guid>id</guid>
      <enclosure type="application/x-shockwave-flash" url="http://www.url.com" />
      <media:content>
        <media:player url="http://www.url.com" />
        <media:credit role="author" scheme="http://www.ur.com">plankbone</media:credit>
        <media:thumbnail url="http://url.com/80281E/u/u/thumbs/2013/Jun/1/5a1ee391e2dd_thumb_2.jpg" width="120" height="90" />
        <media:title>El Reno Tornado 5.31.13</media:title>
        <media:category label="Tags">el reno tornado, tornadoes, twisters, storm chasing,</media:category>
      </media:content>
    </item>

除了从xml文件中抓取缩略图数据之外,这里的代码一切正常。

                XNamespace dcM = "http://search.yahoo.com/mrss/";
                var xdoc = XDocument.Load(url);
                var items = xdoc.Descendants("item")
                .Select(item => new
                {
                    Title = item.Element("title").Value,
                    Description = item.Element("description").Value,
                    Link = item.Element("link").Value,
                    PubDate = item.Element("pubDate").Value,
                    MyImage = (string)item.Elements(dcM + "content")
                   .Select(i=> i.Elements(dcM + "thumbnail"))
                   .Select(i => i.Attribute("url").Value)
                   .SingleOrDefault()
                })
                .ToList();

由于某些原因,我无法从xml获取值。

感谢任何形式的帮助。

如果元素(内容)中没有其他元素(缩略图),则此示例有效:

让我们说xml代码是:

<media:thumbnail url="http://ur.com/bla.jpg" />

这样可行:

MyImage = (string)item.Elements(dcM + "thumbnail")
                   .Select(i => i.Attribute("url").Value)
                   .SingleOrDefault()

2 个答案:

答案 0 :(得分:0)

您可以尝试使用这种方式

XmlDocument doc = new XmlDocument();
doc.Load(url);
XmlNodeList elemList = doc.GetElementsByTagName("media:player");     
for (int i = 0; i < elemList.Count; i++)     
{
    string attrVal = elemList[i].Attributes["url"].Value;
}

答案 1 :(得分:0)

我认为应该是

 MyImage = item.Element(dcM + "content")
               .Element(dcM + "thumbnail")
               .Attribute("url").Value