您好请告诉我如何使用Query从SQL Server中的表生成XML文件。 我的查询是,
select JobTitle as title,PostedDate as date from Jobs
C#代码,
protected void btnXML_Click(object sender, EventArgs e)
{
try
{
DataSet dsJobsDetails = new DataSet();
dsJobsDetails = GetJobDetails();
string fileLoc = @"C:\JobDocuments\jobsxml.xml";
FileStream fs = null;
fs = File.Create(fileLoc);
fs.Close();
if (File.Exists(fileLoc))
{
dsJobsDetails.WriteXml(fileLoc);
}
}
catch { }
}
private DataSet GetJobDetails()
{
DataSet ds = null;
SQLProvider provider = new SQLProvider();
SqlParameter[] paramCandidate = new SqlParameter[2];
try
{
paramCandidate[0] = provider.MakeParameter("JobID", SqlDbType.VarChar, "0");
paramCandidate[1] = provider.MakeParameter("AccountID", SqlDbType.Int, "0");
ds = provider.RunProcedure("Usp_GetJobsDetailsForXML", paramCandidate);
}
catch (Exception ex)
{
SetLastError(ex);
paramCandidate = null;
provider = null;
ds = null;
}
finally
{
paramCandidate = null;
provider = null;
}
return ds;
}
我的存储过程是,
CREATE PROCEDURE [dbo].[Usp_GetJobsDetailsForXML]
(
@JobID varchar(8000),
@AccountID int
)
AS
BEGIN
SET NOCOUNT ON;
select JobTitle as title,PostedDate as date,JobDescription as [description] from Jobs
where JobID in (@JobID)
--FOR XML PATH('Jobs')
END
输出如下,
<NewDataSet>
<Table>
<title>DBA</title>
<date>2014-09-30</date>
</Table>
<Table>
<title>Manager</title>
<date>2014-09-30</date>
</Table>
</NewDataSet>
这里我想将根节点添加为作业,将子根节点添加为作业。我试过了
select JobTitle as title,PostedDate as date from Jobs FOR XML PATH('jobs')
它不起作用。
我想要输出如下,
<jobs>
<job>
<title>
<![CDATA[ DBA ]]>
</title>
<date>
<![CDATA[ 2014-09-30 ]]>
</date>
</job>
<job>
<title>
<![CDATA[ Manager ]]>
</title>
<date>
<![CDATA[ 2014-09-30 ]]>
</date>
</job>
<jobs>
谢谢..
答案 0 :(得分:1)
试试这个
SELECT '<![CDATA[' + JobTitle + ']]>' as title,
'<![CDATA[' + PostedDate + ']]>' as date,
'<![CDATA[' + JobDescription + ']]>' as [description]
FROM Jobs
WHERE JobID in (@JobID)
FOR XML PATH('Job'), ROOT('JOBS')
答案 1 :(得分:0)
DataSet dst = new DataSet("Jobs");
DataTable table = new DataTable("Job");
DataColumn c1 = new DataColumn("Title");
DataColumn c2 = new DataColumn("Date");
table.Columns.Add(c1);
table.Columns.Add(c2);
DataRow row1 = table.NewRow();
row1["Title"] = "T1";
row1["Date"] = "D1";
DataRow row2 = table.NewRow();
row2["Title"] = "T2";
row2["Date"] = "D2";
table.Rows.Add(row1);
table.Rows.Add(row2);
dst.Tables.Add(table);
string p = dst.GetXml();
以下是您需要做的示例。如果您在方法GetJobDetails
中从数据库中获取数据,则应返回DataSet
,DataSetName = "Jobs"
,DataTable
的defaultTableName应为Job!
您没有显示从数据库中获取数据的方法,因为我写了这个例子!
修改强>
首先在btnXML_Click
中写下这样的内容:
DataSet dsJobsDetails = GetJobDetails();
而不是
DataSet dsJobsDetails = new DataSet();
dsJobsDetails = GetJobDetails();
在private DataSet GetJobDetails()
中写这样:
DataSet ds = new DataSet(&#34; Jobs&#34;);
而不是:
DataSet ds = null;
IN SQLProvider
类你应该添加属性TableName,当DataSqlAdapter。填充查询时如下:
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(resultDst, TableName);
}
您需要将属性TableName
值设置为Job