C# C:从XML字符串中选择多个节点
通过下面的代码,我试图在DataGridView中显示XML节点。第一行应该包含红色和蓝色,第二行应该包含绿色和黄色C# C:从XML字符串中选择多个节点,c#,xml,datagridview,nodes,C#,Xml,Datagridview,Nodes,通过下面的代码,我试图在DataGridView中显示XML节点。第一行应该包含红色和蓝色,第二行应该包含绿色和黄色 string xml = "<?xml version="1.0" encoding="utf-8"?> <colors> <color type="string">red</color> <color type="string">blue</color> </colors> <colors
string xml = "<?xml version="1.0" encoding="utf-8"?>
<colors>
<color type="string">red</color>
<color type="string">blue</color>
</colors>
<colors>
<color type="string">green</color>
<color type="string">yellow</color>
</colors>
";
StringReader reader = new StringReader(xml);
XDocument doc = XDocument.Load(reader);
var res = doc.Descendants("colors").Select(n => new { n.Element("color").Value }).ToList());
dataGridView.DataSource = res;
如何为datagridview选择两个颜色值作为结果:
结果
| red | blue |
| green | yellow |
首先,您的xml看起来格式不好。假设是打字错误,你可以使用
var result = doc.Descendants("colors")
.Select(x=>x.Elements("color").Select(c=>c.Value));
输出
如果您希望以显示结果的方式显示结果,则必须做更多的工作,仅使用linq表达式是不够的 首先。按如下方式更改链接查询:
var result = doc.Descendants("colors")
.SelectMany((x) => x.Elements("color").Select((c, i) => new { Id = i, Color = c.Value }));
| red | blue |
| green | yellow |
我们向结果类添加了一个索引,以便以后可以使用它将颜色映射到它们自己的列
接下来,您需要转换数据,否则所有颜色都将放在一列中,因为每个属性都映射到一列:
我在下面的代码中添加了一些注释来解释它的功能
// create a new DataTable for mapping the transformed data
var table = new DataTable();
// loop through all items to create a column for each index.
foreach (var item in result)
{
var colName = item.Id.ToString();
if (!table.Columns.Contains(colName))
{
table.Columns.Add(colName);
}
}
// loop again through the results to add each item to the right position in the datatable
foreach (var item in result)
{
var isMapped = false;
// a second foreach to check if it should go into an existing row
foreach (DataRow dataRow in table.Rows)
{
if (dataRow[item.Id.ToString()].ToString() == "")
{
dataRow[item.Id.ToString()] = item.Color;
isMapped = true; // set to true so we don't map it again later
break; // no need to continue the loop, we found where the color belongs
}
}
if (!isMapped)
{
var row = table.NewRow(); // it doesn't belong in an existing row
row[item.Id.ToString()] = item.Color;
table.Rows.Add(row);
}
}
// Assign the new table to your view
dataGridView1.DataSource = table;
应该这样做。请记住,对于大型数据集,这些循环可能会变慢。可能有一个更为优化的解决方案,但它完成了工作,您现在应该有如下数据:
var result = doc.Descendants("colors")
.SelectMany((x) => x.Elements("color").Select((c, i) => new { Id = i, Color = c.Value }));
| red | blue |
| green | yellow |
OP中的xml似乎格式不好。请验证XML看起来不正确。没有贴色标记谢谢你的评论我更改了xml字符串你好Anu谢谢你的回答但由于某些原因结果不会显示在datagridview中?非常感谢AimusSage!这正是我要找的。