Archive for category ASP.NET/C#

Transforming XML/XSLT using .NET 3.5

Here is a simple example of how you can apply a XSLT stylesheet to a XML file and deliver the result to the browser using ASP.NET 3.5.

default.aspx.cs

using System;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;

public partial class _default : System.Web.UI.Page {

    protected void Page_Load(object sender, EventArgs e) {

        // Source paths
        string xmlFilePath = Server.MapPath("hello-world.xml");
        string xsltFilePath = Server.MapPath("hello-world.xslt");

        // Load XML
        XPathNavigator nav = new XPathDocument(new XmlTextReader(xmlFilePath)).CreateNavigator();

        // Stream for the transformed XML
        MemoryStream stream = new MemoryStream();

        // Load XSLT & transform
        XslCompiledTransform transformer = new XslCompiledTransform();
        transformer.Load(xsltFilePath);
        transformer.Transform(nav, null, stream);

        // Write output
        using (StreamReader reader = new StreamReader(stream)) {
            stream.Position = 0;
            Response.Write(reader.ReadToEnd());
            reader.Close();
        }

    }

}

Yes, that’s it! Here below are the rest of the code used to complete a fully working demo.

default.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="default.aspx.cs" Inherits="_default" %>

hello-world.xml

<?xml version="1.0" encoding="iso-8859-1"?>
<?xml-stylesheet type="text/xsl" href="hello-world.xslt"?>
<text>Hello World!</text>

hello-world.xslt

<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes" />
  <xsl:output method="html"/>

  <xsl:template match="/">
<xsl:text disable-output-escaping="yes">
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
</xsl:text>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title><xsl:value-of select="text"/></title>
  </head>
  <body>
    <h1><xsl:value-of select="text"/></h1>
  </body>
</html>
  </xsl:template>

</xsl:stylesheet>

Tip! To have the HTML doctype declared in your XSLT document you need to wrap it in a <xsl:text> tag with the disable-output-escaping attribute set to yes. And don’t forget to swap the leading and tailing < and > for &lt; and &gt;.

Output

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
  </body>
</html>

,

No Comments

JavaScript for…in

A couple of weeks ago a college of mine got a JavaScript error at one of our SharePoint sites. It turn out, someone at Microsoft has used a for…in loop to iterate over an Array. This works fine as long as you don’t modify the Array object. So when used with Mootools, that adds properties and methods to the Array object, the SharePoint script gets the hick-ups and dies.

The JavaScript documentation states:

Iterates a specified variable over all the properties of an object, in arbitrary order. For each distinct property, the specified statement is executed.

… and

Although it may be tempting to use this as a way to iterate over Array elements, because the for…in statement iterates over user-defined properties in addition to the array elements, if you modify the Array object, such as adding custom properties or methods, the for…in statement will return the name of your user-defined properties in addition to the numeric indexes. Thus it is better to use a traditional for loop with a numeric index when iterating over arrays.

I made a simple example to show the difference between iterating over Arrays and Objects. This is with Mootols included on the page.

JavaScript

console.log('===== Array Example ===== ');

// Array
var a = ['alpha', 'bravo', 'charlie'];
console.log('Creating a new Array:', a);
console.log('The array length is:', a.length);

// For
console.log('--- Start For --- ');
for (var i = 0, j = a.length; i < j; i++) {
    console.log(i, ':', a[i]);
}
console.log('--- End For --- ');

// For-in
console.log('--- Start For-in --- ');
for (var ii in a) {
    console.log(ii, ':', a[ii]);
}
console.log('--- End For-in --- ');

Output

===== Array Example =====
Creating a new Array: ["alpha", "bravo", "charlie"]
The array length is: 3
--- Start For ---
0 : alpha
1 : bravo
2 : charlie
--- End For ---
--- Start For-in ---
0 : alpha
1 : bravo
2 : charlie
$family : Object name=array
each : forEach()
clean : function()
associate : function()
link : function()
contains : function()
extend : function()
getLast : function()
getRandom : function()
include : function()
combine : function()
erase : function()
empty : function()
flatten : function()
hexToRgb : function()
rgbToHex : function()
toJSON : function()
--- End For-in ---

And here using an object.

JavaScript

console.log('===== Object Example =====');

// Object
var o = { 'one': 'alpha', 'Bravo': 'bravo', 'three': 'charlie' };
console.log('Creating a new Array:', o);

// For-in
console.log('--- Start For-in --- ');
for (var item in o) {
    console.log(item, ':', o[item]);
}
console.log('--- End For-in --- ');

Output

===== Object Example =====
Creating a new Array: Object one=alpha Bravo=bravo three=charlie
--- Start For-in ---
one : alpha
Bravo : bravo
three : charlie
--- End For-in ---

Read more about the for…in operation at MDC Core JavaScript 1.5 Guide: Object Manipulation.

Unfortunately this stupid mistake prevents us from using Mootools on this site. And we might have to reconsider the use of Mootols on more sites in the future — AND THAT SUCKS!

, , ,

1 Comment