将XElement转换为Datatable。无法正确使用它

时间:2012-06-24 21:50:10

标签: winforms datagridview linq-to-xml

似乎无法遍历XElement并构建数据表。 我的XElement将在运行时构建,所以我不知道事先的样子 我试图将XElement中的任何内容转换为数据表,以便将其绑定到datagriview。

任何想法我做错了什么?

 static void Main()
    {
        //at runtime could be any object
        const string testXElement = @"<MyObject xmlns=""http://www.test.com/"">
          <code>Test</code>
          <Date>2012-06-24T00:00:00+01:00</Date>
          <Name>John</Name>
        </MyObject>";

        XElement element = XElement.Parse(testXElement);
        var dgv=new DataGridView();

        //Build dataTable from it or 
        var dt=new DataTable();
        XNamespace ns = "http://www.test.com/";
        foreach (var x in element.Elements(ns + "MyObject"))
        {
         //I am never stepping into this one.
           DataColumn dc=new DataColumn();
           dc.ColumnName = x.Name.ToString();
           DataRow row = dt.NewRow();
           row[dc] = x.Value;           
        }
        dgv.DataSource = dt;

    }

1 个答案:

答案 0 :(得分:1)

请改为尝试:

static void Main()
    {
        //at runtime could be any object
        const string testXElement = @"<MyObject xmlns=""http://www.test.com/"">
          <code>Test</code>
          <Date>2012-06-24T00:00:00+01:00</Date>
          <Name>John</Name>
        </MyObject>";


        var dgv=new DataGridView();

        //Build dataTable from it or 
        var dt=new DataTable();
 XmlReader rdr = XmlReader.Create(new System.IO.StringReader(testXElement));
  while (rdr.Read())
  {
           DataColumn dc=new DataColumn();
            dc.ColumnName = x.Name.ToString();
           DataRow row = dt.NewRow();
            row[dc] = x.Value;

        }
        dgv.DataSource = dt;
    }