简体   繁体   English

如何用XElement / XAttribute填充数据表?

[英]How to fill a DataTable with XElement/XAttribute?

I'm new to C#, I never worked with a DataTable before. 我是C#的新手,之前从未使用过DataTable。

I want a DataGridView with specific names. 我想要一个具有特定名称的DataGridView。

        DataTable table = new DataTable();
        List<string> bla = new List<string>();

        XDocument config = XDocument.Load(configFile);

        Dictionary<string, string> dict = config.Descendants("Columns").FirstOrDefault().Elements()
            .GroupBy(x => (string)x.Attribute("XPath"), y => (string)y.Attribute("Name"))
            .ToDictionary(x => x.Key, y => y.FirstOrDefault());

        //I dont know if I need this:
        foreach (string key in dict.Keys)
        {
            table.Columns.Add(key, typeof(string));
        }


        foreach (XElement position in positions.Where(e => e.HasAttributes))
        {
            foreach (XAttribute attribute in position.Attributes().Where(a => dict.ContainsKey($"@{a.Name.LocalName}")))
            {
                string name = attribute.Name.LocalName;
                string value = (string)attribute;
                string xName = dict["@" + name];

                bla.Add(xName);
            }

The columns should have the name from xName. 这些列的名称应来自xName。

How can I do this? 我怎样才能做到这一点?

I've tried this: 我已经试过了:

            foreach (var item in bla)
            {
                DataRow row = table.NewRow();
                row.SetField<string>(item); //this didn't work.

                //foreach (string key in dict.Keys)
                //{
                //    row.SetField<string>(key, item[key]);
                //}
            }

Just want the names from xName as my heading for the output. 只希望xName中的名称作为我的输出标题。

Example für xName: Position, Status, Order, Number, ... As my heading. xName示例:头寸,状态,订单,编号,...作为我的标题。 And under that the values. 并根据该值。

if i understand you correctly, you've got your list of column names ok, but dont know how to create a datatable with the correct column names. 如果我正确理解您的意思,您就可以使用列名列表,但是不知道如何使用正确的列名创建数据表。

Below is an example of how to add a column and row to a datatable with a specific column header name. 以下是如何使用特定的列标题名称向数据表添加列和行的示例。

As discussed in the comments, I've demonstrated a process to get the data you need into a structure that allows you to populate your table. 正如评论中所讨论的那样,我已经演示了一种将所需数据放入允许您填充表的结构中的过程。

      //Class to hold data
  public class MyRecordContent
  {
        public MyRecordContent()
        {
            //initialise list
            RecordsColumns = new List<string>();
        }

        //Holds a list of strings for each column of the record.
        //It starts at position 0 to however many columns you have
        public List<string> RecordsColumns { get; set; }
  }

            //This creates an empty table with the columns
            var myTable = new DataTable("Table1");
            foreach (var item in bla)
            {
                if (!myTable.Columns.Contains(item))
                {
                    myTable.Columns.Add(new DataColumn(item, typeof(string)));
                }
            }



         //Here you build up a list of all records and their field content from your xml.
        foreach (var xmlNode in yourXMLRecordCollection)
        {
            var thisRecord = new MyRecordContent();

            foreach (var xmlCol in xmlNode.Elements)//Each column value
            {
                thisRecord.RecordsColumns.Add(xmlCol.GetValue());
            }

            myListOfRecords.Add(thisRecord);
        }

        foreach (MyRecordContent record in myListOfRecords)
        {
            var row = myTable.NewRow();

            //Here we set each row column values in the datatable.
            //Map each rows column value to be the value in the list at same position.
            for (var colPosition = 0; colPosition <= myTable.Columns.Count - 1;) //Number of columns added.
            {
                row[colPosition] = record.RecordsColumns[colPosition];
            }

            myTable.Rows.Add(row);
        }

In the above, itterate through your list of column names and add each column to the table. 在上面的内容中,遍历您的列名称列表,并将每列添加到表中。 You may want to add a switch statement to the loop to change the datatype of the column based upon name if required. 您可能需要在循环中添加switch语句,以根据名称更改列的数据类型。 Then create of new row off that table and set each fields value accordingly. 然后在该表上创建新行,并相应地设置每个字段的值。 Finally, add the new row to the datatable. 最后,将新行添加到数据表中。

Hope that helps. 希望能有所帮助。

Then 然后

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

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