【IT168技术文档】
我最近需要给用户创建一个feed,所有的数据都是放在sqlserver数据库里的,所以我疯狂的查找把sqlserver里的数据转换成xml的最快速的方法。现在我知道了xml已经成为了sqlserver2005的一部分。
之后我萌生出了一个主意,就是创建一个webservice用于数据库转xml的服务,这样用户就可以在任何时候调用他们需要的数据(如果需要也可以传参数)
现在,我知道你将会说“这不是什么新东西也没有什么难度”,但这正是我写本文的目的,看完本文之后你会发现原来实现这个功能是如此简单。我不敢相信在CodeProject居然没有一个人提出这样的解决方法。
代码
首先,在你的sqlserver2005数据库(要有相关的数据)中创建如下存储过程
其关键的步骤就是“FOR XML PATH(###), ROOT(###)”这部分。他告诉sqlserver返回的xml每一行都要有名为“story”的节点,并且xml文档的根节点名为“stories”CREATE PROCEDURE [dbo].[GetStories] @fromDate datetime, @toDate datetime AS BEGIN select dbo.Story.id, description, notes, text, publicationdate, authorsnames, keywords from dbo.Story inner join dbo.Status on dbo.Story.StatusId = dbo.Status.id where publicationdate between @fromDate and @toDate and dbo.Status.status = 'live' order by publicationDate FOR XML PATH('story'), ROOT('stories') END
下一步新建一个webservice,增加一个新的WebMethod。在这个方法中连接数据库并获得数据。
现在,调用SqlCommand类的ExecuteXmlReader方法以返回xml,类似如下代码
XmlReader reader = command.Command.ExecuteXmlReader();
这个reader就是一个XmlDataDocument流,它可以从WebMethod返回。下面是我写的一段WebMethod,我用了一个数据库帮助类App_Data.SqlSPCommand来获取数据库中的值。
调用webservice就按我们通常做的方法就行,提供一些参数(本例中是两个日期类型)就可以返回xml,本例中返回的xml如下[WebMethod(Description = "Get stories based on a centre, and a from and to date", CacheDuration = 600, MessageName = "GetStoriesForCentre")] public XmlDataDocument GetStoriesForCentre(string centre, DateTime fromDate, DateTime toDate) { Database db = new Database("TarkStoriesConnectionString"); using (db.Connection) { db.OpenConnection(); App_Data.SqlSPCommand command = new App_Data.SqlSPCommand("GetStoriesForCentre", db.Connection); command.AddParameter("@centre", SqlDbType.VarChar, centre); command.AddParameter("@fromDate", SqlDbType.DateTime, fromDate); command.AddParameter("@toDate", SqlDbType.DateTime, toDate); XmlReader reader = command.Command.ExecuteXmlReader(); XmlDataDocument xml = new XmlDataDocument(); xml.Load(reader); return xml; } }
<?xml version="1.0" encoding="utf-8" ?> <stories> <story> <id>514</id> <description>some description</description> <notes>no notes available</notes> <text>blah blah blah</text> <publicationdate>2007-01-30T00:00:00</publicationdate> <authorsnames>Sue Williams</authorsnames> <keywords>boring story</keywords> </story> </stories>