简体   繁体   中英

Add attribute to XML in ASP.NET webservices

I'm new to C# and 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.

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 :

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

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. Please check T-SQL help for the SELECT FOR XML. You can control the structure of the resulting XML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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