开发者

how to convert linq to xml query to string[]

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.Valu开发者_如何学Goe);
 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++; 
                }


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", "..."


Try this

string[] result = (from item in record.Descendants("record").Elements()
                  select item.Value).ToArray();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜