2012-11-04 109 views
2

我有xml,看起来像我在下面。我可以阅读标题,但无法访问媒体网址:内容。有什么建议么?我的非工作的c#与xml一起在下面。需要C#LINQ帮助阅读XML

XNamespace xmlns = "http://www.w3.org/2005/Atom"; 
     var names = 
      (from data in   XDocument.Load("http://channel9.msdn.com/Events/Build/2012/rss").Descendants("item") 
      let xElement = data.Element("title") 
      let xElementUrls = data.Element("media") 
      where xElement != null 
      select new 
         { 
          Title = xElement.Value, 
          Urls = data.Elements(xmlns + "media:group") 
          //MediaGroup = data.Element("media:group") 
         }).ToList(); 

和XML:

<?xml-stylesheet type="text/xsl" media="screen" href="/styles/xslt/rss.xslt"?> 
    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" 
     xmlns:atom="http://www.w3.org/2005/Atom" 
     xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" 
     xmlns:wfw="http://wellformedweb.org/CommentAPI/" 
     xmlns:slash="http://purl.org/rss/1.0/modules/slash/" 
     xmlns:media="http://search.yahoo.com/mrss/" 
     xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" 
     xmlns:c9="http://channel9.msdn.com"> 
    <channel> 

    <item> 
     <title>Building Windows 8 LOB Apps (Repeat)</title> 
     <media:group> 
      <media:content url="http://video.ch9.ms/sessions/build/2012/2-104R.mp4" 
      expression="full" duration="0" fileSize="1" type="video/mp4" medium="video"/> 
      <media:content url="http://video.ch9.ms/sessions/build/2012/2-104R.wmv" 
      expression="full" duration="0" fileSize="1" type="video/x-ms-wmv" medium="video"/> 
     </media:group> 
    </item> 
    <item> 
    <item> 
    ... 
    </item> 
  • 添加此基础上LB的建议,但我无法弄清楚如何让网址的出(现在是返回的URL列表预期每个项目。

    var items = xDoc.Descendants("item") 
        .Where(g => g.Element(media + "group") != null) 
        .Select(g => new { 
            Title = g.Element("title").Value, 
            Url = g.Element(media + "group") 
              .Element(media + "content") 
              .Attribute("url").Value 
            }) 
        .ToList(); 
    

回答

1

media是名称空间别名,而不是元素。

您需要将http://search.yahoo.com/mrss/命名空间内得到group元素:

XNamespace m = "http://search.yahoo.com/mrss/"; 


let xElementUrls = data.Element(m + "group") 
+0

感谢您的所有帮助! –

1

你有错误的命名空间...

XNamespace xmlns = "http://www.w3.org/2005/Atom"; 

应该

XNamespace xmlns = "http://search.yahoo.com/mrss/"; 

而你错误地结合命名空间和元素名称

... 
Urls = data.Elements(xmlns + "group") 
.... 
+0

我觉得我很接近。我仍然没有得到多个网址,只有一个使用L.B的代码。我已经改变它有一些有以下,现在我得到多个网址,但似乎无法拉开它来获得我的url字符串值。 –

2
var xDoc = XDocument.Load("http://channel9.msdn.com/Events/Build/2012/rss"); 
XNamespace media = "http://search.yahoo.com/mrss/"; 

var items = xDoc.Descendants("item") 
      .Where(g => g.Element(media + "group") != null) 
      .Select(g => new { 
          Title = g.Element("title").Value, 
          Url = g.Element(media + "group") 
            .Element(media + "content") 
            .Attribute("url").Value 
          }) 
      .ToList();