C# 将XML文件读入数据表的代码
我编写了下面的代码,它读取给定的xml文件并将内容写入数据表。请不要建议使用LinqToXml,因为该选项已被规定,因为这是一个遗留应用程序C# 将XML文件读入数据表的代码,c#,xml,datatable,C#,Xml,Datatable,我编写了下面的代码,它读取给定的xml文件并将内容写入数据表。请不要建议使用LinqToXml,因为该选项已被规定,因为这是一个遗留应用程序 // create the DataTable that will hold the data DataTable table = new DataTable("ListOfPersonsWithInfo"); // open the file using a Stream
// create the DataTable that will hold the data
DataTable table = new DataTable("ListOfPersonsWithInfo");
// open the file using a Stream
using (Stream stream = new FileStream(fileNameWithAbsolutePath, FileMode.Open, FileAccess.Read))
{
// create the table with the appropriate column names
table.Columns.Add("Name", typeof(String));
table.Columns.Add("ImagePath", typeof(String));
table.Columns.Add("Address", typeof(String));
// use ReadXml to read the XML stream
table.ReadXml(stream);
// tried with this overload-option as well but didnt help
//table.ReadXml(fileNameWithAbsolutePath);
// return the results
return table;
}
但是返回的表包含零行。。。!!!其中,实际的xml文件有“3行”,结构如下(知道这里出了什么问题吗?):
<?xml version="1.0" encoding="utf-8"?>
<Details>
<EachPerson>
<Name>Jack</Name>
<ImagePathAndFileName>C:\Users\Public\Pictures\Sample Pictures\Desert.jpg</ImagePathAndFileName>
<Address>NewYork</Address>
</EachPerson>
<EachPerson>
<Name>Tom</Name>
<ImagePathAndFileName>C:\Users\Public\Pictures\Sample Pictures\Desert.jpg</ImagePathAndFileName>
<Address>London</Address>
</EachPerson>
<EachPerson>
<Name>Jill</Name>
<ImagePathAndFileName>C:\Users\Public\Pictures\Sample Pictures\Desert.jpg</ImagePathAndFileName>
<Address>Tokyo</Address>
</EachPerson>
</Details>
杰克
C:\Users\Public\Pictures\Sample Pictures\Desert.jpg
纽约
汤姆
C:\Users\Public\Pictures\Sample Pictures\Desert.jpg
伦敦
吉尔
C:\Users\Public\Pictures\Sample Pictures\Desert.jpg
东京
您可以使用ReadXML
DataSet ds = new DataSet();
ds.ReadXml(fileNameWithAbsolutePath);
return ds.Tables[0];
就这样,普拉文。。。但是仍然无法理解为什么dataTABLE.ReadXml()失败,而dataSET.ReadXml()工作正常?。。。那么,这个ReadXml.Yes的内部实现是否有特定的内容呢。根目录有三个级别,无法加载到DataTable中。。。你似乎对ADO.NET的内部工作有着非常清晰的认识。以防万一,如果它适合你,你能看看我的另一个问题吗。这个问题没有人试图回答,或者可能对某些人来说太模糊,或者对某些人来说用图表回答太耗时)。