|
|
|
|
|
Home
»
XML and XSLT
»
Transforming XML Documents to HTML using .NET Transformation
|
|
|
|
Author Rank :
|
|
|
Page Views :
|
6274
|
|
Downloads :
|
85
|
|
Rating :
|
Rate it
|
|
Level :
|
Beginner
|
|
|
|
|
Download
Files:
|
|
|
|
|
|
|
|
|
|
|
The XML Data - mcBooks.xml
I have an XML document that stores data about books. Some of the XML tags in the XML document are author name, book title, category, price, and summary. The XML document that stores data looks like the following -
<? xml version="1.0"?> <books> <book> <author>Mahesh Chand</author> <title>A Programmer's Guide to ADO.NET in C#</title> <mclink>http://www.c-sharpcorner.com/Store/1001Details.asp</mclink> <category>ADO.NET/Database/C#/.NET</category> <price currency="USD">44.99</price> <summary> Learn how to write Windows and Web based database applications using ADO.NET and C#. </summary> <About> Mahesh Chand, .NET consultant and author has been working with .NET since its beta released. He is also the founder of C# Corner (http://www.c-sharpcorner.com) and (http://www.mindcracker.com) Web sites. </About> </book> <book> <author>David Talbot and Mahesh Chand</author> <mclink>http://www.c-sharpcorner.com/Store/Books/0732Details.asp</mclink> <title>Applied ADO.NET: Building Data-Driven Solutions</title> <category>ADO.NET/Database/VB.NET</category> <price currency="USD">44.99</price> <summary> Learn how to write Windows and Web based database applications using ADO.NET and VB.NET. </summary> <About> Mahesh Chand, .NET consultant and author has been working with .NET since its beta released. He isalso the founder of C# Corner (http://www.c-sharpcorner.com) and (http://www.mindcracker.com) Web sites. </About> </book> <book> <author>Mahesh Chand</author> <mclink>http://www.c-sharpcorner.com/Store/Books/VisualCsharp.asp</mclink> <title>The Complete Visual C# Programmer's Guide</title> <category>Visual C#/.NET</category> <price currency="USD">59.95</price> <summary> Learn how to write .NET applications using Visual C# </summary> <About> Bulent Ozkir, Mike Gold, Mahesh Chand, Saurabh Nandu, Shivani Maheshwari. </About> </book> </books>
The XSLT File : mcStyles.xsl
The purpose of XSLT file is to define the rules of formatting of XML data. Our XSLT file looks like the following -
<? xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <html> <body> <table border="1" cellpadding="5"> <tr> <th>Title</th> <th>Author</th> <th>Price</th> <th>Category</th> <th>Details</th> <th>About the Author</th> </tr> <!-- Looping --> <xsl:for-each select="books/book" > <xsl:sort select="title" order="descending" /> <tr> <xsl:if test="author='Mahesh Chand'"> <xsl:attribute name="bgcolor">red</xsl:attribute> </xsl:if> <!-- Exporting hyperlink tag --> <td> <a href="{mclink}"><xsl:value-of select="title"/></a> </td> <td><xsl:value-of select="author" /></td> <td><xsl:value-of select="price" /></td> <td><xsl:value-of select="category" /></td> <td><xsl:value-of select="summary" /></td> <td><xsl:value-of select="About" /></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>
The Transformation Process
Once we have the data and the format style sheet, we need to apply the style sheet to the XML document. The .NET framework library provides XslTransform class, which is defined in the System.Xml.Xsl namespace. Before we use this class, we need to add reference to the following namespace:
using System.Xml; using System.Xml.Xsl; using System.Xml.XPath;
Now we can call XslTransform.Transform method, which applies a style sheet to the XML data. The following source code shows we first loads the xsl file using the Load method and calls the Transform method. The Transform method takes two parameters - the source file and the output file name. As you can see, we are using mcBooks.xml as the source file and the output is mcFile.html.
private void TransformBtn_Click(object sender, System.EventArgs e) { XslTransform xslt = new XslTransform(); xslt.Load(@"mcStyles.xsl"); xslt.Transform("mcBooks.xml", "mcFile.html"); }
Note: You can write this code on a button click event handler of a Windows or Web application.
The Output: mcFile.html
Now our formatted XML data looks like Figure 1 in HTML format. As you can see from this figure, we can easily format our XML data and design interactive pages. Now this approach is more useful, when you need to generate customize user interfaces based on the user selections.

Updated Source Code
The above code is obselete. Here is the latest code:
/// <summary> /// Transforms XML to HTML using XSLT /// </summary> /// <param name="xml">XML Document</param> /// <param name="xslt">Stylesheet</param> /// <param name="writer">XmlTextWriter - Output</param> /// <example> /// string xmlFile = @"C:\a.xml"; /// string xslFile = @"C:\b.xsl"; /// XmlTextWriter htmlWriter = new XmlTextWriter(@"C:\output.html", null); /// TransformXML(xmlFile, xslFile, htmlWriter); /// htmlWriter.Close(); /// </example>
public bool TransformXML(string Xml, string Xslt, XmlTextWriter Writer) { XslTransform transformator = new XslTransform(); try { // Load stylesheet transformator.Load(Xslt); // Create DOM Tree XPathDocument document = new XPathDocument(Xml); // Apply transformation transformator.Transform(document, null, Writer, null); } catch(Exception exp) { // To avoid the warning string str = exp.Message; return false; } // Every thing went well return true; }
|
|
Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post
Here.
|
|
|
|
|
Login
to add your contents and source code to this article
|
|
|
|
|
|
|
|
|
|
|
|
Mahesh Chand
Mahesh is the founder of C# Corner and Mindcracker Network, an author of several .NET programming books and a Microsoft MVP for 6 consecutive years. In his day to day work, Mahesh is a Senior Software Consultant with over 14 years of IT industry experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle. If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
|
|
|
|
|
|
|
|
|
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional
consulting company, our consultants are well-known experts in .NET and many of them
are MVPs, authors, and trainers. We specialize in Microsoft .NET development and
utilize Agile Development and Extreme Programming practices to provide fast pace
quick turnaround results. Our software development model is a mix of Agile Development,
traditional SDLC, and Waterfall models.
|
|
Click here to learn more about C# Consulting. |
|
|
|
|
|
|
|
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon.
Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees.
As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
|
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
|
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
|
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
|
|
|
|
|
|
|
|
|
|
|
|
|