1

我目前正在使用带有变量的存储过程从数据库中获取数据,但我是以 XML 格式返回结果。我可以使用此存储过程从表中获取所有数据,并以 XML 形式返回:

public string GetAllPatients()
        {
            string conn = @"Data Source=SNICKERS\SQLEXPRESS;Initial Catalog=VerveDatabase;Integrated Security=True";
            DataSet oDS = new DataSet();
            SqlDataAdapter oCMD = new SqlDataAdapter("getAll", conn);
            oCMD.Fill(oDS, "AllPatients");
            return oDS.GetXml();
        }

但是,当我尝试获取个人患者记录并以 XML 格式返回时,我不确定如何,我目前正在这样做:

public void getUser(int ParticipantID)
        {

            SqlConnection oConn = new SqlConnection();
            oConn.ConnectionString = @"Data Source=SNICKERS\SQLEXPRESS;Initial Catalog=VerveDatabase;Integrated Security=True";
            oConn.Open();
            DataSet oDS = new DataSet();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = oConn;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "getUser";
            cmd.Parameters.Add(new SqlParameter("@ParticipantID",SqlDbType.Int));
            cmd.Parameters["@ParticipantID"].Value = 1; 
            SqlDataReader dr = cmd.ExecuteReader(); 
        }
4

3 回答 3

2

要从 SQL Server 获取 XML,您的存储过程需要读取类似

 SELECT whatever
 FROM thetable
 WHERE ID = @participantID
 FOR XML AUTO

这将生成一个 XML 结果,然后您可以使用

 var xmlResult = dr[0];

编辑澄清

将第二个过程的最后一行中的 datareader 替换为与第一个过程类似的代码

        SqlDataAdapter oCMD = new SqlDataAdapter(cmd); 
        oCMD.Fill(oDS, "User"); 
        return oDS.GetXml(); 
于 2012-07-25T10:37:10.723 回答
1

使用cmd.ExecuteXmlReader()get XmlReader,然后使用其方法(例如ReadOuterXml)来获取 xml。

于 2012-07-25T10:53:15.720 回答
0

要从存储过程返回自定义 xml,请使用 Path 方法。以下是来自 ADventure 作品数据库的示例:

select c.customerID as "@ID",
c.accountnumber as "@AccountNumber",
c.rowguid as "comment()",
CAST('<Test/>' as XML ) as "node()",
c.CustomerType as "AdditionalInfo/@type",
c.modifieddate as "AdditionalInfo/text()",
c.rowguid as "node()"
from Sales.Customer c
where c.CustomerID in ( 1,2)
for xml path('Customer'),root('Customers');

 output

<Customers>
<Customer ID="1" AccountNumber="AW00000001">
  <!--3F5AE95E-B87D-4AED-95B4-C3797AFCB74F-->
  <Test />
  <AdditionalInfo type="S">2004-10-13T11:15:07.263</AdditionalInfo>3F5AE95E-B87D-4AED-95B4-C3797AFCB74F</Customer>
<Customer ID="2" AccountNumber="AW00000002">
  <!--E552F657-A9AF-4A7D-A645-C429D6E02491-->
  <Test />
  <AdditionalInfo type="S">2004-10-13T11:15:07.263</AdditionalInfo>E552F657-A9AF-4A7D-A645-C429D6E02491</Customer>
 </Customers>

要返回一个简单的 xml,请参阅 podiluska 的答案。

于 2012-07-25T10:43:54.987 回答