DataGridView with XML - “合并”子记录

时间:2015-11-03 17:10:48

标签: c# xml datagridview

我有一个简单的Windows窗体应用程序,我正在读取XML文件并在DataGridView中显示它的内容:

DataSet ds = new DataSet();

private void Form1_Load(object sender, EventArgs e)
{
    ds.ReadXmlSchema(@"MySchema.xsd");
    ds.ReadXml(@"MyXML.xml");                       

    dataGridView1.DataSource = ds.Tables[0];
}

这样可以很好地加载父记录。但是,我有一个可选的子记录(位于ds.Tables[1]),我想在dataGridView旁边加载 - 或者在它自己的网格中,或者只是显示在{{}中的数据旁边1}}。

我尝试过几个不同的东西,包括添加第二个DataGridView:

Tables[0] - 这确实显示了数据,但没有迹象表明它实际属于哪个父记录。

合并记录:dataGridView2.DataSource = ds.Tables[1]; - 这会显示我想要的数据,其中空白表示特定行不包含此信息。但是,当我保存数据时,它会将所有内容写入ds.Tables[0].Merge(ds.Tables[1]);,这是我不希望发生的。

我只想并排显示这些数据(模仿Tables[0]操作的效果,但继续写入各自的行。

我目前正在使用Merge编写数据。 有谁能指出我正确的方向?

编辑:

XML文件的基本布局是:

ds.WriteXml(@"Path@");

1 个答案:

答案 0 :(得分:2)

您可以使用XML Linq像这样解析xml文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;


namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            var results = doc.Element("parent").Elements().Select(x => new
            {
                name = x.Name,
                property1 = x.Attribute("property1").Value,
                property2 = x.Attribute("property2").Value,
                child_property1 = x.Element("optionalchild") == null ? null : x.Element("optionalchild").Attribute("property1").Value,
                child_property2 = x.Element("optionalchild") == null ? null : x.Element("optionalchild").Attribute("property2").Value
            }).ToList();

        }
    }
}
​