XDocument / Linq Combines Attributes as a Comma Separated List

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 get the message "Hello, Foo" using LINQ. Notation.

I can get "Hello" using

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

I can get all the attributes using

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

How do I get a list of string attribute values ​​so that I can join it as a comma separated list?

+4
source share
2 answers

So, thanks to womp, I realized that it was the Select method that I need in order to get the Value property so that I can get an array of strings. Therefore, the following work is performed.

 String.Join(",", (string[]) xDocument.Element("RootElement").Elements("ChildElement").Attributes("Attribute1").Select(attribute => attribute.Value).ToArray()); 
+2
source
 var strings = from attribute in xDocument.Descendants("ChildElement").Attributes() select attribute.Value; 
+2
source

All Articles