C# 在ASP.NET Web服务中将属性添加到XML
我不熟悉C#和ASP.NET 我设法将MS SQL Server数据库放入xml文档中,但我现在要做的是,在xml中添加一个属性,该属性将是数据库中的C# 在ASP.NET Web服务中将属性添加到XML,c#,asp.net,xml,web-services,C#,Asp.net,Xml,Web Services,我不熟悉C#和ASP.NET 我设法将MS SQL Server数据库放入xml文档中,但我现在要做的是,在xml中添加一个属性,该属性将是数据库中的id 比如: <Products> <product id=1> <name>Some name</name> </product> <product id=2> <name>Some other</n
id
比如:
<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>
我是在linux机器上回答的,所以现在手头没有SQL Server。请查看T-SQL帮助以获取SELECT for XML。您可以控制生成的XML的结构。最简单的方法是在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;
}
}
.asmx
web服务已失效-检查WCF或新的ASP.NET WebAPI for REST服务我得到错误SQLException未处理…
关于字符串xmlContents
@knowbody:您的连接字符串不完整-您有数据源(服务器名称),但没有数据库名称。。。。。尝试以下操作:string conString=“server=my_db.com;数据库=XXXXXXXXX;综合安全=真实代码>并用实际数据库名称替换XXXXXX现在一切都好了。^另外,如果您得到null
,您可以将sqlCmd.ExecuteScalar作为字符串执行,但一切正常。超级老派。非常感谢。
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;
}
}