views:

313

answers:

1

Given this XML ...

<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"&gt;
 <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>

And this C# code:

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

I know the Xdoc is not empty and contains the right XML.

I also implemented some ScottGu code (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) as a sanity check and it works exactly as expected.

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);
        }
+7  A: 

Xml namespaces:

    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 };
Marc Gravell
thank you, thank you, thank you. I was beating my head against the wall for about 2 hours on that one. wish I could vote more than once.
Kyle West
Me too - I didn't know about doc.Descendants and always used doc.Elements()!
Perhentian