2013-08-20 63 views
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(); 
} 

回答

0

它看起来像你的DataSet可以只读一次一个XML文件。

ds.ReadXml(ms); 

尝试,如果您可以通过XmlReader中得到所有3个XML文件。这会告诉你一些事情。

+0

我试过XmlDocument.Parse(MemoryStream),但也有同样的问题! – Nishant