在ASP.NET webservices中将属性添加到XML

时间:2015-02-22 10:59:26

标签: c# asp.net xml web-services

我是C#和ASP.NET的新手

我设法将MS SQL Server数据库放入xml文档中,但我现在要做的是,向XML添加一个属性,该属性将是数据库中的id。 / p>

类似的东西:

<Products>
    <product id=1>
        <name>Some name</name> 
    </product>
    <product id=2>
        <name>Some other</name> 
    </product>
    <product id=3>
        <name>Some other name</name> 
    </product>
</Products>

这是我到目前为止: products.asmx.cs

[WebMethod]
public XmlDocument productsAll()
{
    string conString = "Data Source=my_db.com;Integrated Security=True";
    SqlConnection sqlConn = new SqlConnection(conString);

    SqlCommand sqlCmd = sqlConn.CreateCommand();
    sqlCmd.CommandType = CommandType.Text;
    sqlCmd.CommandText = "SELECT * FROM Products";

    SqlDataAdapter dataAdptr = new SqlDataAdapter();
    dataAdptr.SelectCommand = sqlCmd;
    DataSet dsProducts = new DataSet("Products");
    dataAdptr.Fill(dsProducts, "product");

    XmlDocument xmlDom = new XmlDocument();
    xmlDom.LoadXml(dsProducts.GetXml());
    return xmlDom;
}

2 个答案:

答案 0 :(得分:2)

最简单的方法是在SQL Server中创建XML,然后只读出生成的XML。

尝试这样的事情:

public XmlDocument productsAll()
{
    // define connection string
    string conString = "Data Source=my_db.com;Integrated Security=True";

    // define SQL query to use 
    string query = "SELECT ID AS '@ID', Name FROM dbo.Products FOR XML PATH('Product'), ROOT('Products')";

    // set up connection and command objects
    using (SqlConnection sqlConn = new SqlConnection(conString))
    using (SqlCommand sqlCmd = new SqlCommand(query, sqlConn))
    {
       // open connection
       sqlConn.Open();

       // execute query, read out the XML from the T-SQL query
       string xmlContents = sqlCmd.ExecuteScalar().ToString();

       // close connection
       sqlConn.Close();

       // parse XML received from SQL Server into a XmlDocument and return
       XmlDocument xmlDom = new XmlDocument();
       xmlDom.LoadXml(xmlContents);

       return xmlDom;
    }
}

答案 1 :(得分:0)

我正在从linux机器上回答,所以现在没有方便的SQL Server。请检查SELECT FOR XML的T-SQL帮助。您可以控制生成的XML的结构。