将 XML 文件读入 DataTable 的代码 [英] Code for reading an XML file into a DataTable
本文介绍了将 XML 文件读入 DataTable 的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我编写了以下代码段,它读取给定的 xml 文件并将内容写入数据表.请不要建议使用 LinqToXml,因为该选项已被排除,因为这是一个遗留应用程序.
I have written the following piece of code that reads through a given xml-file and writes the contents into a data-table. Please do NOT suggest to use LinqToXml as that option is ruled because this is a legacy application.
// 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:UsersPublicPicturesSample PicturesDesert.jpg</ImagePathAndFileName>
<Address>NewYork</Address>
</EachPerson>
<EachPerson>
<Name>Tom</Name>
<ImagePathAndFileName>C:UsersPublicPicturesSample PicturesDesert.jpg</ImagePathAndFileName>
<Address>London</Address>
</EachPerson>
<EachPerson>
<Name>Jill</Name>
<ImagePathAndFileName>C:UsersPublicPicturesSample PicturesDesert.jpg</ImagePathAndFileName>
<Address>Tokyo</Address>
</EachPerson>
</Details>
推荐答案
可以使用 ReadXML
You can use ReadXML
DataSet ds = new DataSet();
ds.ReadXml(fileNameWithAbsolutePath);
return ds.Tables[0];
这篇关于将 XML 文件读入 DataTable 的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文