问题描述
我的客户给了我一个用ColdFusion编写的 webservice
,我一直在试图用C#来消费它。我一直在尝试将XML转换为 DataTabl
e,但是我得到一个没有行的 DataTable
。
这是我的XML:
<?xml version ='1.0' ='是'?>
< dt确认>
< 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){
//创建DataTable将保存数据
DataTable table = new DataTable(dtFirms);
尝试
{
//使用Stream
打开文件(Stream stream = GenerateStreamFromString(s))
{
//创建表具有相应的列名称
table.Columns.Add(NR,typeof(string));
table.Columns.Add(NAME,typeof(string));
table.Columns.Add(NRTIT,typeof(string));
table.Columns.Add(PERIOD,typeof(int));
//使用ReadXml读取XML流
table.ReadXml(stream);
//返回结果
返回表;
}
}
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;
返回流;
}
它始终返回空的DataTable。我究竟做错了什么?请帮助我。
-
您可以为xml文件创建模式。 p>
-
通过使用XSD.exe可以为模式生成类结构。使用这些xml模式类遍历xml文件。
-
使用table.Rows.Add()函数在数据表中添加条目。
My customer gave me a webservice
which was written in ColdFusion and I have been trying to consume it with C#. I have been trying to convert XML to DataTabl
e but I am getting a DataTable
with no rows.
Here is my 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. It always return empty 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. What am I doing wrong? Please help me.
You can create schema for your xml file.
By using XSD.exe you can generate class structure for schema. Use these xml schema classes for iterating through the xml file.
Use table.Rows.Add() function to add entries in data table.
这篇关于如何将xml转换为DataTable在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!