tags:

views:

53

answers:

2

here is my xml:

<record>
<id>12342</id>
<name>xx</name>
<blah1>asdfas</blah1>
<blah2>asdfas</blah2>
.....
</record>

I would like to get all of the values and put it into a array. i tried the following, it returns "12342xxasdfasasdfas" instead of "12342","xx","asdfas","asdfas"

  var q = record.Elements("record").Select(r=>r.Value);
 string[] array = q.ToArray();

i have come up the solution by using foreach loop, just wondering if there are any better ways to do that?

var q2 = record.Descendants("record").Elements();
int length = Convert.ToInt32(q2.Count().ToString());
string[] array2 =new string[length];
int i = 0;
                foreach (XElement e in q2)
                {
                    array2[i] = e.Value;
                   i++; 
                }
A: 

Try this

string[] result = (from item in record.Descendants("record").Elements()
                  select item.Value).ToArray();
CRice
This only works if the text we’re looking for is in an immediate child node of `<record>`. Granted, the example is like that, but the question didn’t state that it should be limited that way.
Timwi
I'm just answering the question not imagining things that might be required
CRice
A: 

To extract all the text elements, look for the XText nodes in the structure and extract their values:

string[] array = record.DescendantNodes()
                       .Where(n => n.NodeType == XmlNodeType.Text)
                       .Select(n => ((XText) n).Value)
                       .ToArray();

Result in your example: "12342", "xx", "asdfas", "asdfas", "..."

Timwi