从SQL Server 2005返回的XML原始数据从.NET调用时不正确不正确、原始数据、Server、SQL

2023-09-07 08:59:41 作者:柠夏

我有一个存储过程返回XML原始数据 FOR XML RAW 类似的格式如下:

I have a stored procedure that returns XML raw data FOR XML RAW something like the following format:

<row 
    codelistid="1" codelistname="LOCATION" 
    codeid="1557" codename="Hors Ile de France" languageid="1" />

当我运行Management Studio中的存储过程的1765行价值的数据返回,但是当我打电话的过程,从我的C#code这似乎是围绕一半882.看来,如果两行有同样的codeID那么只有一个返回

When I run the stored procedure in Management Studio 1765 rows worth of data is returned but when I call the procedure from my C# code it appears to be around half of that 882. It seems that if two rows have the same codeid then only one is returned

我是用的XMLReader返回XML逐行再追加每行作为的XElement,以我的成绩的XDocument。

I am using the xmlreader to return the XML row by row and then appending each row as an XElement to my results XDocument.

下面是我如何检索数据:

Here is how I am retrieving the data:

 using (SqlConnection conn = new SqlConnection(con))
        {
            XDocument results = new XDocument(
           new XElement("results"));

            using (SqlCommand cmd = conn.CreateCommand())
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "MyStoredProc";
                conn.Open();
                var count = 0;
                using (XmlReader reader = cmd.ExecuteXmlReader())
                {

                    while (reader.Read())
                    {

                        results.Root.Add(XElement.Parse(reader.ReadOuterXml()));
                        count += 1;

                    }
                }

                return results;

            }
        }

如果我的存储过程改变输出数据,而不是XML,并通过SqlDataReader的阅读它似乎很好地工作。

If I change the SPROC to output the data rather than XML and read it via SQLDataReader it seems to work fine.

任何人有为什么发生这种情况,我会像理想数据库返回的XML什么想法?

Anyone have any ideas on why this is happening as I would ideally like the database to return the XML?

在此先感谢。

推荐答案

reader.Read() reader.ReadOuterXml()在同一回路是将跳过一行。试试这个:

reader.Read() and reader.ReadOuterXml() being in the same loop would skip one line. Try this :

using (XmlReader reader = cmd.ExecuteXmlReader())
            {
               reader.Read(); //For initial first read.
               while (!reader.EOF)
                {

                    results.Root.Add(XElement.Parse(reader.ReadOuterXml()));
                    count += 1;

                }
            }