我如何将xml读入DataTable类型对象?

时间:2013-11-14 09:36:05

标签: c# .net xml datatable dataset

如果我将xml读取到DataSet

,我没有问题
DataSet temp = new DataSet();
temp.ReadXml(UncompressedStream, System.Data.XmlReadMode.Auto);

但如果我使用DataTable

DataTable temp = new DataTable();
temp.ReadXml(UncompressedStream);

然后数据表不加载数据(列数和行数等于0)

我如何阅读xml到DataTable

我的临时解决方案:

DataSet temp = new DataSet();
DataTable structure = new DataTable();
temp.ReadXml(UncompressedStream, System.Data.XmlReadMode.Auto);
structure = temp.Tables[0];

2 个答案:

答案 0 :(得分:1)

private static void DemonstrateReadWriteXMLDocumentWithString()
{
    DataTable table = CreateTestTable("XmlDemo");
    PrintValues(table, "Original table");

    string fileName = "C:\\TestData.xml";
    table.WriteXml(fileName, XmlWriteMode.WriteSchema);

    DataTable newTable = new DataTable();
    newTable.ReadXml(fileName);

    // Print out values in the table.
    PrintValues(newTable, "New table");
}

private static DataTable CreateTestTable(string tableName)
{
    // Create a test DataTable with two columns and a few rows.
    DataTable table = new DataTable(tableName);
    DataColumn column = new DataColumn("id", typeof(System.Int32));
    column.AutoIncrement = true;
    table.Columns.Add(column);

    column = new DataColumn("item", typeof(System.String));
    table.Columns.Add(column);

    // Add ten rows.
    DataRow row;
    for (int i = 0; i <= 9; i++)
    {
        row = table.NewRow();
        row["item"] = "item " + i;
        table.Rows.Add(row);
    }

    table.AcceptChanges();
    return table;
}

来自:microsoft - xml - datatable

检查在此代码中,他们为表添加名称,并创建行和列。

答案 1 :(得分:0)

LINQ to XML可能是你正在寻找的东西。