gpt4 book ai didi

c# - 将 XML 文件读入 DataTable 的代码

转载 作者:数据小太阳 更新时间:2023-10-29 02:00:48 26 4
gpt4 key购买 nike

我编写了以下代码,它读取给定的 xml 文件并将内容写入数据表。请不要建议使用 LinqToXml,因为该选项已被规定,因为这是一个遗留应用程序。

            // 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>

最佳答案

您可以使用 ReadXML

        DataSet ds = new DataSet();
ds.ReadXml(fileNameWithAbsolutePath);
return ds.Tables[0];

关于c# - 将 XML 文件读入 DataTable 的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9781796/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com