Thursday, July 9, 2009

Please help me about ASP .NET and XML?

Hi, I'm using C# for my programs.





I developed some web applications in ASP before but now I get into the ASP .NET.





I want to return an XML page as response. My question is how can I do that? In other words should I use WebFroms (.aspx) or web service (.asmx) or etc...?

Please help me about ASP .NET and XML?
There are many ways to do this, but my suggestion is to use an HTTP Handler. If you are using ASP.Net 2.0, you can create a file in the App_Code directory that implements the IHttpHandler. Here is a simple example:





using System;


using System.Data;


using System.Configuration;


using System.Xml;


using System.Text;


using System.Web;


using System.Web.Security;


using System.Web.UI;


using System.Web.UI.WebControls;


using System.Web.UI.WebControls.WebParts;


using System.Web.UI.HtmlControls;





/// %26lt;summary%26gt;


/// Summary description for XMLHandler


/// %26lt;/summary%26gt;


public class XMLHandler:IHttpHandler


{





#region IHttpHandler Members





bool IHttpHandler.IsReusable


{


get { return false; }


}





void IHttpHandler.ProcessRequest(HttpContext context)


{


XmlTextWriter writer = new XmlTextWriter(context.Response.OutputStr... Encoding.UTF8);


writer.WriteStartDocument();


writer.WriteStartElement("Customers");


writer.WriteStartElement("Customer");


writer.WriteStartElement("FirstName");


writer.WriteString("Brian");


writer.WriteEndElement(); //FirstName


writer.WriteStartElement("LastName");


writer.WriteString("G");


writer.WriteEndElement();//LastName


writer.WriteEndElement();//Customer


writer.WriteEndElement();//Customers


writer.WriteEndDocument();


writer.Flush();


writer.Close();


}





#endregion


}





In your web.config file, add the following block inside your %26lt;system.web%26gt; element:





%26lt;httpHandlers%26gt;


%26lt;add verb="*" path ="MyXmlFile.aspx" type ="XMLHandler"/%26gt;


%26lt;/httpHandlers%26gt;





Then, any request made to http://yoursite/MyXmlFile.aspx will use the HTTP handler and render this xml document:





%26lt;?xml version="1.0" encoding="utf-8" ?%26gt;


%26lt;Customers%26gt;


%26lt;Customer%26gt;


%26lt;FirstName%26gt;Brian%26lt;/FirstName%26gt;


%26lt;LastName%26gt;G%26lt;/LastName%26gt;


%26lt;/Customer%26gt;


%26lt;/Customers%26gt;





By customizing the ProcessRequest method of the HTTP handler, you can get your XML from a database or load it from a file.





If the XML is meant to be used by an application, you probably want to use a web service.
Reply:Look into serialization. Its best to have a webservice handle this and pass off the xml to your asp.net page. then just take the xml and deserialize it to display it on the page.


No comments:

Post a Comment