It was one of my experience in leading a team to create a multiskin mobile application. How do we do it? We don’t use the Mobile Control which is provided in .NET Framework, instead we use the XML to XHTML using XSLT approach. XSLT really come to handy when you need to do some transformation on XML data
.NET Framework has provided the easy way to handle with XML and XSLT in System.Xml, System.Xml.XPath and System.Xml.Xsl.
We are going to create a simple Windows Application using C# to show you how to do it, quite simple actually.
private void btnTransform_Click(object sender, System.EventArgs e) { try { if (txtXML.Text == string.Empty || txtXSL.Text == string.Empty) { txtResult.Text = "Please complete XML / XSL"; } else { StringReader sr = new StringReader(txtXML.Text); XPathDocument xpd = new XPathDocument(sr); XslTransform xslt = new XslTransform(); StringReader srt = new StringReader(txtXSL.Text); XmlTextReader xtr = new XmlTextReader(srt); xslt.Load(xtr, null); StringWriter sw = new StringWriter(); XmlTextWriter xtw = new XmlTextWriter(sw); xtw.Indentation = 2; xtw.Formatting = Formatting.Indented; xslt.Transform(xpd, null, sw, null); txtResult.Text = sw.ToString(); tabControl1.SelectedTab = tabResult; sr.Close(); xtr.Close(); sw.Close(); xtw.Close(); } } catch (Exception ex) { txtResult.Text = ex.Source + "\r\n" + ex.Message + "\r\n" + ex.StackTrace; } }
Basically, the above code will load the XML data in txtXML and XSL template in txtXSL and use the XslTransform Transform method to do transformation.
The following will show the XML to XHTML transformation.
First, paste the following XML data to txtXML.
<posts>
<post id="1">
<title>First article</title>
<author>Oskar</author>
</post>
<post id="2">
<title>Second article</title>
<author>Oskar</author>
</post>
</posts>
Also paste the following XSL template to txtXSL.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="posts">
<html>
<head>
<title>XML to XHTML Example</title>
</head>
<body>
<table>
<xsl:apply-templates select="post" />
</table>
</body>
</html>
</xsl:template>
<xsl:template match="post">
<tr>
<td><xsl:value-of select="@id" /></td>
<td><xsl:value-of select="title" /></td>
<td><xsl:value-of select="author" /></td>
</tr>
</xsl:template>
</xsl:stylesheet>
Click on Transform button, the result will be:
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=utf-16">
<title>XML to XHTML Example</title>
</head>
<body>
<table border="1">
<tr>
<td>1</td>
<td>First article</td>
<td>Oskar</td>
</tr>
<tr>
<td>2</td>
<td>Second article</td>
<td>Oskar</td>
</tr>
</table>
</body>
</html>
That completes the initial requirement for this approach, different browser request can be served using different template. Of course, you need to sharpen your skill in XML, XPath Query, XSLT. Have a great day.
Popularity: 2% [?]
RSS feed for comments on this post · TrackBack URI
Leave a reply