如何读取XML到一个DataTable? [英] How to read XML into a DataTable?
本文介绍了如何读取XML到一个DataTable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串
内存正是一些像这样的XML:
I have some XML in a string
in memory exactly like this:
<symbols>
<symbol>EURCHF</symbol>
<symbol>EURGBP</symbol>
<symbol>EURJPY</symbol>
<symbol>EURUSD</symbol>
</symbols>
我要读入到此一数据表
。我是这样做的:
DataTable dt = new DataTable();
dt.TableName = "symbols";
dt.Columns.Add("symbol");
if (!String.IsNullOrEmpty(symbols))
{
dt.ReadXml(new StringReader(symbols));
}
然而,当我检查的行数,数据表
结束有零行。什么?我做错了。
However when I check the number of rows, the DataTable
ends up having zero rows. What am I doing wrong?
推荐答案
从这里开始:的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;
}
}
您可能想看一看的 DataTable.ReadXml 法
编辑:如果你有XML对象在内存中就可以直接使用ReadXml方法。 DataTable.ReadXml(MemoryStream的对象);
If you have xml object in memory you can use the ReadXml method directly. DataTable.ReadXml(MemoryStream Object);
编辑2:我做的出口。以下XML架构是必需的:
EDIT 2: I did the export. The following XML Schema is required:
<?xml version="1.0" standalone="yes"?>
<DocumentElement>
<symbols>
<symbol>EURCHF</symbol>
</symbols>
<symbols>
<symbol>EURGBP</symbol>
</symbols>
<symbols>
<symbol>EURJPY</symbol>
</symbols>
</DocumentElement>
这篇关于如何读取XML到一个DataTable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文