当执行linq到xml并在datagridview中显示数据时,我的代码只解析目录文件夹中的一个文件

时间:2011-09-13 17:29:44

标签: c# xml datagridview linq-to-xml

为什么在linq到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";

    }  
}

1 个答案:

答案 0 :(得分:2)

您正在迭代目录中的文件 - 但每次只需重新分配数据源。换句话说,它与earlier question中的问题完全相同,只是它与三个查询不同,而是为每个文件重新分配。

请尝试使用单个查询:

var query = from file in fileEntries
            let doc = XDocument.Load(file)
            from x in doc.Descendants("XAxisCalib")
                         .Concat(doc.Descendants("YAxisCalib"))
                         .Concat(doc.Descendants("ZAxisCalib"))
            select new
            {
                // Include this to see the file for each value
                File = file,
                MaxChild = x.Element("Max").Value,
                MinChild = x.Element("Min").Value
            };

var bs3 = new BindingSource { DataSource = query };

dataGridView1.AutoGenerateColumns = true;
dataGridView1.AutoSize = true;

dataGridView1.DataSource = bs3;

编辑:好的,如果你知道每个元素中只有一个,那就相当容易了:

var query = from file in fileEntries
            let doc = XDocument.Load(file)
            let x = doc.Descendants("XAxisCalib").Single()
            let y = doc.Descendants("YAxisCalib").Single()
            let z = doc.Descendants("ZAxisCalib").Single()
            select new
            {
                // Include this to see the file for each value
                File = file,
                MaxChildX = x.Element("Max").Value,
                MinChildX = x.Element("Min").Value,
                MaxChildY = y.Element("Max").Value,
                MinChildY = y.Element("Min").Value,
                MaxChildZ = z.Element("Max").Value,
                MinChildZ = z.Element("Min").Value
            };