【问题标题】:how to convert xml to DataTable in C#如何在 C# 中将 xml 转换为 DataTable
【发布时间】:2014-04-01 12:46:46
【问题描述】:

我的客户给了我一个webservice,它是用 ColdFusion 编写的,我一直在尝试用 C# 来使用它。我一直在尝试将 XML 转换为 DataTable,但我得到了一个没有行的 DataTable

这是我的 XML:

<?xml version='1.0' standalone='yes'?>
<dtFirms>
  <NR>2</NR>
  <NAME>CS Net - 2014</NAME>
  <NRTIT>2 - 2014 - CS Net - 2014</NRTIT>
  <PERIOD>7</PERIOD>
</dtFirms>

这是我的 C# 代码。它总是返回空的 DataTable。我做错了什么?

    public DataTable ReadXmlIntoDataTable(string s) {

    //create the DataTable that will hold the data
    DataTable table = new DataTable("dtFirms");
    try
    {
        //open the file using a Stream
        using (Stream stream = GenerateStreamFromString(s))
        {
            //create the table with the appropriate column names
            table.Columns.Add("NR", typeof(string));
            table.Columns.Add("NAME", typeof(string));
            table.Columns.Add("NRTIT", typeof(string));
            table.Columns.Add("PERIOD", typeof(int));

            //use ReadXml to read the XML stream
            table.ReadXml(stream);

            //return the results
            return table;
        }
    }
    catch (Exception ex)
    {
        return table;
    }
}


public Stream GenerateStreamFromString(string s)
{
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(s);
    writer.Flush();
    stream.Position = 0;
    return stream;
}

它总是返回空的DataTable。我究竟做错了什么?请帮帮我。

【问题讨论】:

标签: c# xml datatable


【解决方案1】:
  1. 您可以为您的 xml 文件创建架构。

  2. 通过使用 XSD.exe,您可以生成架构的类结构。使用这些 xml 模式类来遍历 xml 文件。

  3. 使用 table.Rows.Add() 函数在数据表中添加条目。

【讨论】:

    猜你喜欢
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 2010-11-09
    • 2021-06-24
    • 2013-10-14
    相关资源
    最近更新 更多