简体   繁体   English

XML Linq读取多个节点

[英]XML Linq Reading multiple nodes

I'm trying to extract data from a wordpress blog xml feed, this is the format of the xml: http://brockallen.com/category/asp-net/feed/ 我正在尝试从wordpress博客xml提要中提取数据,这是xml的格式: http : //brockallen.com/category/asp-net/feed/

var xElements = XElement.Parse(ResponseText);
var blogs = (from temp in xElements.Elements()
             select new 
             {
                 Title = temp.Element("item").Element("title").Value,
                 URL = temp.Element("item").Element("link").Value,
                 Image = temp.Element("item").Element("media:content").Value
             }).FirstOrDefault();

How do I get them all, and store them in to an object? 如何获得所有这些并将它们存储到一个对象中?

Error on media:content is saying The ':' character, hexadecimal value 0x3A, cannot be included in a name.` media:content上的错误是说':'字符,十六进制值0x3A,不能包含在名称中。

When I remove that line, it only gets one, when there are more, even after removing FirstOrDefault() 当我删除该行时,即使删除了FirstOrDefault()之后,它也只会得到一行。

Your are working on the wrong level of the document. 您正在处理错误的文档级别。 Also you need an namespace. 您还需要一个名称空间。

  XNamespace media = "http://search.yahoo.com/mrss/";
  var items =
  from channelElement in XElement.Parse(ResponseText).Element("channel").Elements("item")
  select new {
    Title = channelElement.Element("title").Value,
    Url = channelElement.Element("link").Value,
    MediaItems = (
        from mediaItemElement in channelElement.Elements(media + "content")
        select new {
            url = mediaItemElement.Attribute("url").Value,
            medium = mediaItemElement.Attribute("medium").Value
            }
        ).ToList()
  };

Try this...updated with namespace for querying content element 试试这个...用名称空间更新以查询content元素

    // var xDoc = XDocument.Load(@"<your xml location>");
    var xDoc = XDocument.Parse("<your xml string>");
    XNamespace ns = "http://search.yahoo.com/mrss/";

    var blogs = (from temp in xDoc.Descendants().Elements("item")
                 select new
                 {
                     Title = temp.Element("title").Value,
                     URL = temp.Element("link").Value,
                     Image = temp.Element(ns + "content").Value
                 });

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

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