0
我試圖讀取多個XML文件中的數據,但遇到以下情況除外:ADO.NET - 錯誤讀取多個XML文件
「意外的XML聲明XML聲明必須在第一個節點。文件,並且不允許在它之前出現空格字符 11895行,位置3。
在這種情況下,我試圖在循環中讀取3個文件。如果每個文件都是單獨讀取的,它可以正常工作。只有在循環中連續讀取文件時,讀取第二個文件時發生異常。在上面的例外中,file1有11895行,所以當讀取file2時,它會引發'11895行意外的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();
}
我試過XmlDocument.Parse(MemoryStream),但也有同樣的問題! – Nishant