[英]how to convert xml to DataTable in C#
My customer gave me a webservice
which was written in ColdFusion and I have been trying to consume it with C#. 我的客户给了我一个用ColdFusion编写的webservice
,我一直在尝试使用C#来使用它。 I have been trying to convert XML to DataTabl
e but I am getting a DataTable
with no rows. 我一直在尝试将XML转换为DataTabl
e,但是我得到的DataTable
没有行。
Here is my XML: 这是我的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>
and this is my C# code. 这是我的C#代码。 It always return empty DataTable. 它总是返回空的DataTable。 What am I doing wrong? 我究竟做错了什么?
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;
}
It always return empty DataTable. 它总是返回空的DataTable。 What am I doing wrong? 我究竟做错了什么? Please help me. 请帮我。
You can create schema for your xml file. 您可以为xml文件创建架构。
By using XSD.exe you can generate class structure for schema. 通过使用XSD.exe,可以生成架构的类结构。 Use these xml schema classes for iterating through the xml file. 使用这些xml模式类来遍历xml文件。
Use table.Rows.Add() function to add entries in data table. 使用table.Rows.Add()函数在数据表中添加条目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.