简体   繁体   English

如何将linq转换为xml查询到字符串[]

[英]how to convert linq to xml query to string[]

here is my xml: 这是我的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" 我尝试了以下操作,它返回的是“ 12342xxasdfasasdfas”,而不是“ 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? 我已经通过使用foreach循环提出了解决方案,只是想知道是否有更好的方法来做到这一点?

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

Try this 尝试这个

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

To extract all the text elements, look for the XText nodes in the structure and extract their values: 要提取所有文本元素,请在结构中查找XText节点并提取其值:

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

Result in your example: "12342", "xx", "asdfas", "asdfas", "..." 您的示例的结果:“ 12342”,“ xx”,“ asdfas”,“ asdfas”,“ ...”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM