为什么LINQ to XML Query不工作(Amazon S3)

Kyl*_*est 8 .net c# linq-to-xml

鉴于此XML ...

<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
 <Name>public.rpmware.com</Name>
 <Prefix></Prefix>
 <Marker></Marker>
 <MaxKeys>1000</MaxKeys>
 <IsTruncated>false</IsTruncated>
 <Contents>
  <Key>0.dir</Key>
  <LastModified>2008-06-25T16:09:49.000Z</LastModified>
  <ETag>"0ba2a466f9dfe225d7ae85277a99a976"</ETag>
  <Size>16</Size>
  <Owner>
   <ID>1234</ID>
   <DisplayName>kyle</DisplayName>
  </Owner>
  <StorageClass>STANDARD</StorageClass>
 </Contents>
 <!-- repeat similar 100x -->     
</ListBucketResult>
Run Code Online (Sandbox Code Playgroud)

这个C#代码:

XDocument doc =  XDocument.Load(xmlReader);
var contents = from content in doc.Descendants("Contents") select new {Key = content.Element("Key").Value, ETag = content.Element("ETag").Value};

        foreach (var content in contents)
        {
            Console.WriteLine(content.Key);
            Console.WriteLine(content.ETag);
        }
Run Code Online (Sandbox Code Playgroud)

我知道Xdoc不是空的并且包含正确的XML.

我还实现了一些ScottGu代码(http://weblogs.asp.net/scottgu/archive/2007/08/07/using-linq-to-xml-and-how-to-build-a-custom-rss-feed -reader-with-it.aspx)作为一个完整性检查,它完全按预期工作.

XDocument doc2 = XDocument.Load(@"http://weblogs.asp.net/scottgu/rss.aspx");
        var posts = from items in doc2.Descendants("item") select new { Title = items.Element("title").Value };
        foreach (var post in posts)
        {
            Console.WriteLine(post.Title);
        }
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 12

Xml名称空间:

    XNamespace ns = "http://s3.amazonaws.com/doc/2006-03-01/";
    var contents = from content in doc.Descendants(ns + "Contents")
                   select new { Key = content.Element(ns + "Key").Value,
                       ETag = content.Element(ns + "ETag").Value };
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你,谢谢你,谢谢你.那个人在我的头上撞了大约2个小时.希望我能不止一次投票. (2认同)
  • 我也是 - 我不知道doc.Descendants并且总是使用doc.Elements()! (2认同)