简体   繁体   English

在ASP.NET Web服务中向XML添加属性

[英]Add attribute to XML in ASP.NET webservices

I'm new to C# and ASP.NET 我是C#和ASP.NET的新手

I managed to put MS SQL Server database into xml document, but what I'm trying to do now is, to add an attribute to the XML, which will be an id from the database. 我设法将MS SQL Server数据库放入xml文档中,但是我现在想做的是向XML添加一个属性,该属性将是数据库的id

something like: 就像是:

<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>

This is what I have so far: 这是我到目前为止的内容:
products.asmx.cs : 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;
}

The easiest way would be to create the XML in SQL Server and just read out the resulting XML. 最简单的方法是在SQL Server中创建XML,然后只读取生成的XML。

Try something like this: 尝试这样的事情:

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;
    }
}

I'm answering from a linux machine so don't have SQL Server handy right now. 我正在从Linux机器上回答,所以现在没有SQL Server可用。 Please check T-SQL help for the SELECT FOR XML. 请检查T-SQL帮助以获取SELECT FOR XML。 You can control the structure of the resulting XML. 您可以控制生成的XML的结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM