ADO.NET - 读取多个xml文件时出错

时间:2013-08-20 21:20:36

标签: c# ado.net xmlreader memorystream

我正在尝试从多个XML文件中读取数据,但遇到以下异常:

“意外的XML声明.XML声明必须是文档中的第一个节点,并且不允许在它之前显示空白字符。 第11895行,第3位。“

在这种情况下,我试图在循环中读取3个文件。如果单独读取每个文件,它可以正常工作。只有在循环中连续读取文件时,读取第二个文件时才会发生异常。在上面的例外中,file1有11895行,所以当读取file2时,它会在第11895行抛出“Unexpected XML声明”,因为每个文件都有自己的XML声明。

我的问题是:如果使用新的DataSet和MemoryStream对象来读取每个文件,那么为什么它不允许第二和第三个文件具有XML声明头?如何使每个阅读独立于前一个阅读?

这是我的代码:

//Open the database connection
using (SqlConnection cn = new SqlConnection(Properties.Settings.Default.ApplicationServices))
{
    cn.Open();
    // Begin a new transaction
    using (SqlTransaction tr = cn.BeginTransaction())
    {
        try
        {
            //Loop through each attachment, convert the attachment xml to DataTable and Load into the Database
            foreach (Attachment att in message.Attachments)
            {
                LogMessage(string.Format("Reading Attachment: {0}", att.Name), 0);
                // Load the Contents of the attachment into a MemoryStream
                using (MemoryStream ms = new MemoryStream(att.Content, true))
                {
                    ms.Seek(0, System.IO.SeekOrigin.Begin);
                    //Use a dataset to automatically determine the schema from the XML file
                    using (DataSet ds = new DataSet())
                    {
                        //Load the MemoryStream contents into a DataSet, that automatically determines the schema
                        try
                        {
                            ds.ReadXml(ms);
                            ms.Dispose();
                        }
                        catch (Exception ex)
                        {
                            LogMessage(string.Format("Error reading xml {0}. {1}{2}", att.Name, ex.Message, ex.StackTrace), 2);
                            throw ex;
                        }

                        LogMessage(string.Format("Found {0} records", ds.Tables[0].Rows.Count), 0);

                        /*Other business logic to process data in the ds.Tables[0] ... */
                    }
                }
            }

            //Commit transaction if everything worked out fine
            LogMessage("Card product import complete, committing transaction", 0);
            tr.Commit();
        }
        catch (Exception ex)
        {
            LogMessage("Error Occured during card product import, rolling back transaction", 2);
            tr.Rollback();
            throw ex;
        }
    }
    cn.Close();
}

1 个答案:

答案 0 :(得分:0)

看起来您的DataSet一次只能读取一个xml文件。

 ds.ReadXml(ms);

尝试通过XmlReader获取所有3个xml文件。那会告诉你一些事情。