以前在一个公司项目中要用数据库中的记录生成相应的xml文件[主要是为了提高访问速度],但由于当时资料的缺乏,在开发过程中遇到了不过的困难,好在最终完成了工作,我在这里把当时其中的一个功能函数列出来,其于的函数大同小意,希望兄弟们以后在遇到这样的问题时不象我当初一样再吃苦头.![]()
using system;
using system.collections;
using system.componentmodel;
using system.data;
using system.diagnostics;
using system.web;
using system.web.services;
using system.xml;
using system.data.sqlclient;
using system.configuration;
using system.text;
using system.xml.xsl;
using system.io;
namespace admin
{
/// <summary>
/// createxml 的摘要说明。
/// </summary>
///
[system.web.services.webservice(namespace="http://..../admin/createxml.asmx",description="生成或更新星迷俱乐部中的xml文件")]
public class createxml : system.web.services.webservice
{
public createxml()
{
//codegen: 该调用是 asp.net web 服务设计器所必需的
initializecomponent();
}
#region 组件设计器生成的代码
//web 服务设计器所必需的
private icontainer components = null;
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void initializecomponent()
{
}
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void dispose( bool disposing )
{
if(disposing && components != null)
{
components.dispose();
}
base.dispose(disposing);
}
#endregion
[webmethod]
public string createclubxmlbyid(string id)
{
datetime filenamedate=datetime.now;
createpath("..\\"+filenamedate.year.tostring(),filenamedate.month.tostring()+"_"+filenamedate.day.tostring());//按时期生成相应的时期型文件夹
string filename=server.mappath("..\\"+filenamedate.year.tostring()+"\\"+filenamedate.month.tostring()+"_"+filenamedate.day.tostring()+"\\club"+id.trim()+".xml");
xmltextwriter picxmlwriter = null;
encoding gb = encoding.getencoding("gb2312");
picxmlwriter = new xmltextwriter (filename,gb);
try
{
string strconn=configurationsettings.appsettings["starclub"];
string sqlstatement="select * from club where id="+id.tostring().trim();
sqlconnection myconnection= new sqlconnection(strconn);
sqldataadapter mycommand = new sqldataadapter(sqlstatement,myconnection);
dataset mydataset;
mycommand.selectcommand.commandtype=commandtype.text;
mydataset = new dataset();
mycommand.fill(mydataset, "mytable");
picxmlwriter.formatting = formatting.indented;
picxmlwriter.indentation= 6;
picxmlwriter.namespaces = false;
picxmlwriter.writestartdocument();
//picxmlwriter.writedoctype("文档类型", null, ".xml", null);
//picxmlwriter.writecomment("按在数据库中记录的id进行记录读写");
picxmlwriter.writeprocessinginstruction("xml-stylesheet","type='text/xsl' href='../../xsl/1.xsl'") ; //写入用于解释的xsl文件名
picxmlwriter.writestartelement("","club","");
foreach(datarow r in mydataset.tables[0].rows) //依次取出所有行
{
picxmlwriter.writestartelement("","record","");
foreach(datacolumn c in mydataset.tables[0].columns) //依次找出当前记录的所有列属性
{
if ((c.caption.tostring()!="pic"))
{
picxmlwriter.writestartelement("",c.caption.tostring().trim(),""); //写入字段名
picxmlwriter.writestring(r[c].tostring().trim()); //写入数据