0

複数の XML ファイルからデータを読み取ろうとしていますが、次の例外が発生します。

「予期しない XML 宣言です。XML 宣言はドキュメントの最初のノードである必要があり、その前に空白文字を使用することはできません。行 11895、位置 3。」

この場合、ループで読み取ろうとしている 3 つのファイルがあります。各ファイルを個別に読み取ると、正常に動作します。ファイルがループで連続して読み取られる場合にのみ、2 番目のファイルの読み取り中に例外が発生します。上記の例外では、file1 には 11895 行があったため、file2 を読み取ると、「11895 行で予期しない XML 宣言」がスローされます。これは、各ファイルに独自の XML 宣言があるためです。

私の質問は: 新しい DataSet と MemoryStream オブジェクトを使用して各ファイルを読み取る場合、2 番目と 3 番目のファイルに 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();
}
4

1 に答える 1

0

DataSet は一度に 1 つの xml ファイルしか読み取れないようです。

 ds.ReadXml(ms);

XmlReader を介して 3 つの xml ファイルをすべて取得できるかどうか試してください。それはあなたに何かを教えてくれます。

于 2013-08-20T23:35:35.813 に答える