views:

721

answers:

2

If I have the following xml:

        XDocument xDocument = new XDocument(
            new XElement("RootElement",
                new XElement("ChildElement",
                    new XAttribute("Attribute1", "Hello"),
                    new XAttribute("Attribute2", "World")
                ),
                new XElement("ChildElement",
                    new XAttribute("Attribute1", "Foo"),
                    new XAttribute("Attribute2", "Bar")
                )
            )
        );

I'm after the output "Hello, Foo" using LINQ "." notation.

I can get "Hello" using

xDocument.Element("RootElement").Element("ChildElement").Attribute("Attribute1").Value;

I can get all of the Attributes using

xDocument.Element("RootElement").Elements("ChildElement").Attributes("Attribute1");

How can I get a list of the string values of the attributes so that I can join then as a comma separated list?

+1  A: 
var strings = from attribute in 
                       xDocument.Descendants("ChildElement").Attributes()
              select attribute.Value;
womp
I needed to do it using the . notation rather than using linq query. Howeverr, +1 as you totally pointed me in the right direction.
Robin Day
Ah sorry, I usually use the query syntax just out of habit.
womp
+2  A: 

Ok, so thanks to womp I realised it was the Select method I needed in order to obtain the property Value so I could get an array of strings. Therefore, the following works.

String.Join(",", (string[]) xDocument.Element("RootElement").Elements("ChildElement").Attributes("Attribute1").Select(attribute => attribute.Value).ToArray());
Robin Day