如何将XML读入DataTable?

Mar*_*son 9 c# xml datatable

string在内存中有一些XML,如下所示:

<symbols>
  <symbol>EURCHF</symbol>
  <symbol>EURGBP</symbol>
  <symbol>EURJPY</symbol>
  <symbol>EURUSD</symbol>
</symbols>
Run Code Online (Sandbox Code Playgroud)

我想把它读成一个DataTable.我是这样做的:

DataTable dt = new DataTable();
dt.TableName = "symbols";
dt.Columns.Add("symbol");

if (!String.IsNullOrEmpty(symbols))
{
    dt.ReadXml(new StringReader(symbols));
}
Run Code Online (Sandbox Code Playgroud)

但是当我检查行数时,DataTable最终会有零行.我究竟做错了什么?

Ase*_*tam 15

从这里:http://www.dreamincode.net/code/snippet3186.htm

// <summary>
/// method for reading an XML file into a DataTable
/// </summary>
/// <param name="file">name (and path) of the XML file</param>
/// <returns></returns>
public DataTable ReadXML(string file)
{
    //create the DataTable that will hold the data
    DataTable table = new DataTable("XmlData");
    try
    {
        //open the file using a Stream
        using(Stream stream = new  FileStream(file, FileMode.Open, FileAccess.Read))
        {
            //create the table with the appropriate column names
            table.Columns.Add("Name", typeof(string));
            table.Columns.Add("Power", typeof(int));
            table.Columns.Add("Location", typeof(string));

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

            //return the results
            return table;
        }                
    }
    catch (Exception ex)
    {
        return table;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可能想看一下DataTable.ReadXml方法.

编辑:如果你在内存中有xml对象,你可以直接使用ReadXml方法. DataTable.ReadXml(MemoryStream Object);

编辑2:我做了出口.需要以下XML Schema:

<?xml version="1.0" standalone="yes"?>
<DocumentElement>
  <symbols>
    <symbol>EURCHF</symbol>
  </symbols>
  <symbols>
    <symbol>EURGBP</symbol>
  </symbols>
  <symbols>
    <symbol>EURJPY</symbol>
  </symbols>
</DocumentElement>
Run Code Online (Sandbox Code Playgroud)

  • 最有可能是架构问题.尝试创建类似的数据表并调用WriteXML.然后检查写入的内容并与xml进行比较.这应该清楚为什么数据表是空的怀疑. (3认同)