Mega Code Archive

 
Categories / ASP.Net Tutorial / XML
 

Transform XML document to HTML

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"  Inherits="XmlToHtml" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">     <title>Untitled Page</title> </head> <body>     <form id="form1" runat="server">     <div>          </div>     </form> </body> </html> File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; 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; using System.Xml.Xsl; using System.Xml.XPath; using System.Xml; public partial class XmlToHtml : System.Web.UI.Page {     protected void Page_Load(object sender, EventArgs e)     {     string xslFile = Server.MapPath("Data.xslt");     string xmlFile = Server.MapPath("Data.xml");     string htmlFile = Server.MapPath("Data.htm");     XslTransform transf = new XslTransform();     transf.Load(xslFile);     transf.Transform(xmlFile, htmlFile);     XPathDocument xdoc = new XPathDocument(new XmlTextReader(xmlFile));     XPathNavigator xnav = xdoc.CreateNavigator();     XmlReader reader = transf.Transform(xnav, null);     reader.MoveToContent();     Response.Write(reader.ReadOuterXml());     reader.Close();     } } File: Data.xml <?xml version="1.0"?> <Data>    <DVD ID="1" Category="Category 1">       <Title>title 1</Title>       <Director>directory 2</Director>       <Price>1</Price>       <Starring>          <Star>star 1</Star>          <Star>star 2</Star>       </Starring>    </DVD>    <DVD ID="2" Category="Category 2">       <Title>title 2</Title>       <Director>directory 2</Director>       <Price>2</Price>       <Starring>          <Star>star 3</Star>          <Star>star 4</Star>       </Starring>    </DVD> </Data> File: Data.xsl <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">   <xsl:output method="xml"/>   <xsl:template match="/">     <xsl:element name="Movies">       <xsl:apply-templates select="//DVD" />     </xsl:element>   </xsl:template>   <xsl:template match="DVD">     <xsl:element name="{name()}">       <xsl:attribute name="ID">         <xsl:value-of select="@ID"/>       </xsl:attribute>       <xsl:attribute name="Title">         <xsl:value-of select="Title/text()"/>       </xsl:attribute>       <xsl:apply-templates select="Starring" />     </xsl:element>   </xsl:template>   <xsl:template match="Starring">     <xsl:element name="Stars">       <xsl:attribute name="Name">         <xsl:value-of select="Star/text()"/>       </xsl:attribute>     </xsl:element>   </xsl:template>    </xsl:stylesheet>