将XML文件读入DataTable的代码

4
我编写了以下代码,它可以读取给定的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>
1个回答

11
您可以使用ReadXML。
        DataSet ds = new DataSet();
        ds.ReadXml(fileNameWithAbsolutePath);
        return ds.Tables[0];

这就是问题所在,PraVn... 但我仍然无法理解为什么 dataTABLE.ReadXml() 失败了,而 dataSET.ReadXml() 却成功了?是否与 ReadXml 的内部实现有关呢? - MukeshAnAlsoRan
1
是的。 <Details> 是根节点,有三个层级,无法在数据表中加载。 - PraveenVenu
谢谢PraVn...您似乎对ADO.NET的内部工作有非常清晰的了解。如果方便的话,您能否看一下我的另一个问题http://stackoverflow.com/questions/9687640/uml-diagram-for-ado-net-components-like-dataadapter-dataset-datatable-etc。这个问题没有人尝试回答,或者对某些人来说太模糊,或者对某些人来说回答带有图表可能需要太多时间。 - MukeshAnAlsoRan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接