如何从存储过程返回xml以在C#中解析

时间:2017-09-28 17:44:18

标签: c# sql-server xml stored-procedures model-view-controller

我有一个存储过程,我用它来生成我使用XML序列化的对象列表。需要将XML对象从数据库服务器发送到服务器端,在服务器端将在控制器操作中对其进行解析。出于某种原因,在执行SqlCommand的行(using (XmlReader xmlReader = cmd.ExecuteXmlReader()))处引发异常并返回错误:

  

将数据类型varchar转换为bigint时出错

在存储过程中,我通过创建这样的根来构建XML对象:

Declare @xmlRoot AS XML
set @xmlRoot = '<SubscriptionsRoot></SubscriptionsRoot>'

然后我将子对象添加到它中:

set @xmlRoot.modify('insert sql:variable("@XML3")  into (/SubscriptionsRoot)[1]')

set @xmlRoot.modify('insert sql:variable("@XML2")  into (/SubscriptionsRoot)[1]')

最后,为了从存储过程返回xml,我选择它:

select @xmlRoot

在控制器动作中,我有:

using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings....))
{
    SqlCommand cmd = new SqlCommand();

    cmd.CommandText = "dbname.sp_name";
    cmd.Parameters.Add("@newSubscrXml", SqlDbType.VarChar).Value = newSubscrStr;
    cmd.Parameters.Add("@inactiveSubscrStr", SqlDbType.VarChar).Value = existingSubSecurityIds;
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Connection = sqlConnection;

    sqlConnection.Open();

    SqlDataReader reader;    

    using (XmlReader xmlReader = cmd.ExecuteXmlReader())
    {
        while (xmlReader.Read())
        {
            var s = xmlReader.ReadOuterXml();
        }
    }

    sqlConnection.Close();
}

可能导致此问题的原因是什么?如何从存储过程返回xml并在C#中解析?

编辑:以下是xml对象的结构

<SubscriptionsRoot>
  <NotReSubscribed>
    <Subscription>
      <attribute_1>5645</attribute_1>
      <attribute_2>4336565           </attribute_2>
      <attribute_3>gfghgh             </attribute_3>
      <attribute_4>32345        </attribute_4>
      <attribute_5>not Resubscribed</attribute_5>
    </Subscription>
    <Subscription>
      <attribute_1>5435</attribute_1>
      <attribute_2>3446554           </attribute_2>
      <attribute_3>6dgdhgh             </attribute_3>
      <attribute_4>gdh5435354        </attribute_4>

      <attribute_5>not Resubscribed</attribute_5>
    </Subscription>
    <Subscription>
      <attribute_1>23456</attribute_1>
      <attribute_2>h23454           </attribute_2>
      <attribute_3>s345345             </attribute_3>
      <attribute_4>jfgh23454        </attribute_4>
      <attribute_5>not Resubscribed</attribute_5>
    </Subscription>
  </NotReSubscribed>
  <NotNewlySubscribed>
    <Subscription>
      <attribute_3>hjh554</attribute_3>
      <attribute_2>         </attribute_2>
      <attribute_3>sd34534</attribute_3>
      <attribute_4>fsdghfgdhdfgh</attribute_4>
    </Subscription>
    <Subscription>
      <attribute_3>86785</attribute_3>
      <attribute_2>         </attribute_2>
      <attribute_3>a234424</attribute_3>
      <attribute_4>98796896dgf</attribute_4>

    </Subscription>
  </NotNewlySubscribed>
</SubscriptionsRoot>

0 个答案:

没有答案