我正在尝试从多个 XML 文件中读取数据,但遇到以下异常:
“意外的 XML 声明。XML 声明必须是文档中的第一个节点,并且在它之前不允许出现空白字符。第 11895 行,位置 3。”
在这种情况下,我试图循环读取 3 个文件。如果单独读取每个文件,则可以正常工作。只有在循环中连续读取文件时,才会在读取第二个文件时发生异常。在上面的异常中,file1 有 11895 行,所以在读取 file2 时它会抛出“Unexpected XML declaration at line 11895”,因为每个文件都有自己的 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();
}