0

似乎无法遍历 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;

    }
4

1 回答 1

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;
    }
于 2012-06-24T23:59:54.093 回答