当执行 linq to xml 并在 datagridview 中显示数据时,我的代码仅解析目录文件夹中的一个文件
为什么在 linq to xml 解析期间我的代码只读取文件夹中的 xml 文件之一而不是全部?
private void button1_Click(object sender, EventArgs e)
{
string[] fileEntries = Directory.GetFiles(@"", "*.cfg*");
foreach (string fileName in fileEntries)
{
XDocument doc = XDocument.Load(fileName);
var query = from x in doc.Descendants("")
select new
{
MaxChild = x.Element("Max").Value,
MinChild = x.Element("Min").Value
};
var query2 = from y in doc.Descendants("")
select new
{
MaxChild = y.Element("Max").Value,
MinChild = y.Element("Min").Value
};
var query3 = from z in doc.Descendants("")
select new
{
MaxChild = z.Element("Max").Value,
MinChild = z.Element("Min").Value
};
var bs3 = new BindingSource { DataSource = query.Union(query2.Union(query3)) };
dataGridView1.AutoGenerateColumns = true;
dataGridView1.AutoSize = true;
dataGridView1.DataSource = bs3;
dataGridView1.Columns[0].HeaderText = "Max";
dataGridView1.Columns[1].HeaderText = "Min";
}
}
How come during the linq to xml parse my code is only reading one fo the xml files in the folder rather than all of them?
private void button1_Click(object sender, EventArgs e)
{
string[] fileEntries = Directory.GetFiles(@"", "*.cfg*");
foreach (string fileName in fileEntries)
{
XDocument doc = XDocument.Load(fileName);
var query = from x in doc.Descendants("")
select new
{
MaxChild = x.Element("Max").Value,
MinChild = x.Element("Min").Value
};
var query2 = from y in doc.Descendants("")
select new
{
MaxChild = y.Element("Max").Value,
MinChild = y.Element("Min").Value
};
var query3 = from z in doc.Descendants("")
select new
{
MaxChild = z.Element("Max").Value,
MinChild = z.Element("Min").Value
};
var bs3 = new BindingSource { DataSource = query.Union(query2.Union(query3)) };
dataGridView1.AutoGenerateColumns = true;
dataGridView1.AutoSize = true;
dataGridView1.DataSource = bs3;
dataGridView1.Columns[0].HeaderText = "Max";
dataGridView1.Columns[1].HeaderText = "Min";
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在迭代目录中的文件 - 但每次只需重新分配数据源。换句话说,这与您的 之前的问题,只不过它不是与三个查询有关,而是与为每个文件重新分配它有关。
请尝试使用单个查询:
编辑:好的,如果您知道每个元素恰好只有一个,那么这相当简单:
You're iterating over the files in the directory - but simply reassigning the datasource each time. In other words, it's exactly the same problem as in your earlier question, except that instead of it being to do with three queries, it's to do with reassigning it for each file.
Try this instead, using a single query:
EDIT: Okay, if you know there's going to be exactly one of each element, it's fairly easy: