applying xslt to xml using asp

Upload: priteshp2

Post on 08-Apr-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/7/2019 Applying XSLT to XML Using ASP

    1/12

    Applying XSLT to XML Using ASP.NET(Page 1 of 5 )

    This article explains the basics of XSL to transform XML documents usingsimple examples. We will gradually focus on using ASP.NET to implement XSLT

    for any XML document and even to database queries. It introduces differentways of implementing XSL from browsers perspective and servers perspective.We will also discuss some tips to generate automated XML from databasequeries and then transform them to HTML using XSL transformations.

    Introduction to XSL

    Anyone who designs web pages using any tool/designer would certainly knowabout what CSS is. We use HTML in combination with CSS to design andpresent web pages in a more efficient manner. Basically a style sheet presentsa sheet of styles, which would affect certain tag(s) in a web document. By

    modifying the underlying style sheets, sometimes the look and feel of entirewebsite gets changed dramatically.

    As HTML is made up of standard pre-defined tags, we can simply design andapply style sheets for necessary tags using CSS, and browser can understandall those details very easily. But any XML document is generally designed usinguser-defined tags (elements) to which browser may not understand all thosenew tags (elements). Just like we use CSS to present HTML document in a well-formatted and understandable manner, we use XSL to present (transform) anXML document in any format we require.

    XSL stands for eXtensible Stylesheet Language. It is a language used to designand apply style sheets especially for XML documents. Originally the researchstarted to provide style sheet technology to XML using XSL, but finally endedup with three more divisions of XSL. So, XSL now consists of three partsnamely XSLT, XPath and XSL-FO. XSLT is a language for transforming XMLdocuments (even today, several programmers call XSLT as XSL). XPath is alanguage to filter, search or sort information available in XML documents. XSL-FO is a language for formatting XML documents. In this article we mainly focuson XSLT, which stands for XSL Transformations.

    XSLT can also be used to transform an XML document to another XML

    document (it need not be only HTML document). Another beauty of XSLT isthat it internally works/traverse using XPath language. We can even concludethat The better we learn about XPath, the better XSLT we can design.Although this article mainly focuses on XSL, I suggest you to go through thefundamentals of XPath language for a better understanding (but not necessaryfor this article).

  • 8/7/2019 Applying XSLT to XML Using ASP

    2/12

    Another important issue is that not all the browsers can understand XSLTtechnology. Specifically old browsers like IE5, IE5.5, Netscape 4 etc, are notcompatible with XSL or XSLT files to the full-fledged recommendations of W3C.They were developed on a working draft of W3C, which was not yet completedby the time of their releases. IE6 or above and NN6 or above are completely

    compatible with standard XSL(T) specifications recommended by W3C. But ifwe use any server side programming to implement XSLT (like ASP.NET), we canovercome the compatibility issues of any browser (as the transformation takesplace at server without browsers knowledge). This issue is deeply examined inthe later part of this article.

    Applying XSLT to XML Using ASP.NET - A Simple Example on XSLT(Page 2 of 5 )

    Just to understand the structure of XSLT, let us test a small example on XSLTusing a simple XML document without using any server-side (ASP.NET) code.

    This example can be directly executed by opening the XML document in anyXSLT supported browser (currently I tested with IE6).

    So, let us start by creating a plain and simple XML document (sample1.xml) asfollows.

    Stuart

    28

    Now we create an XSL style sheet (sample1.xslt) for the above XML documentas follows.

    Name of Employee :
    Age:

  • 8/7/2019 Applying XSLT to XML Using ASP

    3/12

    Remember that the family of XML technologies are case sensitive. By this time,if you open sample1.xml directly in IE6 or NN6, you should be able to see the

    result something like the following:

    Name of Employee: StuartAge: 28

    If you observe the HTML source at browser, it would be something like thefollowing, which is nothing but the transformation applied through XSLT to theXML document:

    Name of Employee : Stuart
    Age:28

    Let us try to understand the above two files in detail now. sample1.xml is justa simple XML document. sample1.xslt is our style sheet definition totransform sample1.xml. If we carefully observe the sample1.xml file, we canspot an interesting line:

    This is the only magic needed in any XML file to be transformed to any XSLT.The above statement instructs browser to link the current XML document withsample1.xslt and present (transform) it accordingly. So, in general we will notsee the XML document as a tree structure anymore. It will be presented(transformed) in a different way as specified in sample1.xslt.

    Now, let us study the most important lines in sample1.xslt.

    The above line defines that it is basically an XSLT document used for certaintransformation.

    The above line specifies the format (template) applicable to the root of XMLdocument. We can also specify individual templates for each and every XML

  • 8/7/2019 Applying XSLT to XML Using ASP

    4/12

    element as well. The attribute match can be provided with any XPathexpression.

    And finally, the above line states that it has to get the value (text) present inthat path (Employees/Employee/Name) of XML document (tree) starting fromroot. In this case it starts from root (/), then searches for Employees element(first element), within that Employee child element (first child element) andfinally the child element Name (first child element) of Employee element. Thispath could be replaced with any XPath expression.

    The rest of the content should be easily understandable, as it mostly containsXHTML elements to be transformed. Make sure that this example always takesonly the first elements into consideration. There is no use of placing more thanone employee information in sample1.xml file. We will overcome this drawback

    in the later part of this article.

    Applying XSLT to XML Using ASP.NET - XSLT with ASP.NET(Page 3 of 5 )

    The above example works well with IE6 or other latest browsers (which supportXSLT), but what about the situation of old browsers? Our sample examplewould never work on those browsers. To overcome this problem, we shift XMLand XSLT to the server side programming that supports these technologies.One of them is ASP.NET. I further extend the previous sample example withrespect to ASP.NET using a simple web form with few lines of ASP.NET code.

    Open your Visual Studio.NET and create a new ASP.NET project. Add the abovetwo files (sample1.xml and sample1.xslt) to the project. Drag an XML controlfrom toolbox on to the webform. Press F7 (code window) and copy the followingtwo statements at the top:

    Imports System.XmlImports System.Xml.Xsl

    Copy the following code in the page load event of that webform.

    Dim docXML As New XmlDocumentdocXML.Load(Server.MapPath("sample1.xml"))Dim docXSL As New XslTransformdocXSL.Load(Server.MapPath("sample1.xslt"))Xml1.Document = docXMLXml1.Transform = docXSL

  • 8/7/2019 Applying XSLT to XML Using ASP

    5/12

    I think the above code is self-explanatory. Basically, we are creating two objectsdocXML (to hold an XML document) and docXSL (to hold an XSL document).Using the Load method, we are loading the two files in to the respectiveobjects. We assign both of them to the XML server control (xml1) provided inASP.NET. The transformation gets implemented automatically at run-time

    without any extra hurdle!!

    Press F5 to execute the web application and you should be able to see the sameoutput to which you have seen earlier. By now, we designed a web applicationusing XML and XSLT, which is completely browser independent.

    But, always designing static XML documents may not be helpful in all thesituations. What if I want to have a dynamically generated XML to betransformed through XSLT? The next section addresses this issue in a verypleasant manner.

    Applying XSLT to XML Using ASP.NET - Query a Database and Transformthrough XSLT using ASP.NET(Page 4 of 5 )

    In this section, we will generate XML dynamically (using the ADO.NET relatedXML architecture) for any query issued to a database, and finally transform itbased on a particular XSLT file. We will implement the same strategy as above,but with little bit modifications to deal with database queries effectively.

    Create a new ASP.NET project in VS.NET. Drag an XML control from toolbox onto the webform. Press F7 (code window) and copy the following two statements

    at the top:

    Imports System.XmlImports System.Xml.Xsl

    Add a new method to the class as following:

    Private Function getXMLContent(ByVal SQL As String) As XmlDocumentDim ds As New DataSet("SQLData")Dim da As New SqlDataAdapter(SQL, "data source=.;initial

    catalog=northwind;user id=sa")

    da.Fill(ds, "Rows")da.Dispose()Dim sw As New System.IO.StringWriterds.WriteXml(sw)ds.Dispose()

    Dim docXML As New XmlDocumentdocXML.LoadXml(sw.ToString())

  • 8/7/2019 Applying XSLT to XML Using ASP

    6/12

  • 8/7/2019 Applying XSLT to XML Using ASP

    7/12

    Till now we worked with only one record using XSLT. But what if we want morethan one record to be transformed using XSLT? This section addresses thoseneeds. We shall further enhance the example in previous section so that it cantransform more than one order from orders table at a time.

    In the example given in previous section, the SELECT retrieves only one row (asit is filtered by orderID). We need to change it, so that it can retrieve more thanone row. Make the modification to the above statement as following:

    Dim docXML As XmlDocument = getXMLContent("select top 10 orderid,freightfrom orders ")

    The above SELECT statement retrieves only first 10 orders (of course you cangive any query you require). Now, we need to make few more changes toFormat1.xslt file. Modify the Format1.xslt file so that it looks consistent withthe following code:

    OrderIDFreight

    Let us examine the modified code:

  • 8/7/2019 Applying XSLT to XML Using ASP

    8/12

    element can be used to select every XML element of a specifiednode set. It is quite similar to for loop. As we are filtering to some extent using element, element should be given with morespecific information excluding the filtering.

    Press F5 to execute the web application and you should be able to see a tableof 10 orders from database transformed using XSLT.

    Closing Remarks

    I suggest you to learn XPath language to design XSLT very effectively. As thisarticle mainly focuses on basics of XSLT, I could not give any information onXPath. I examined these examples using Microsoft SQL Server 2000 EnterpriseEdition and Visual Studio.NET 2003 Enterprise Architect. But all the abovesamples would definitely work with any database (provided you makemodifications to the .NET data provider). And it is not at all necessary to have

    Visual Studio.NET to work with XSLT. You can also implement the in-lineapproach of ASP.NET to get the things worked out. By designing XSLT with abit analysis, you can design templates for entire web site (for look and feelcompatibility). These templates could be reused for new web applicationswithout any hurdle. Complicated reports can also be designed using XSLT.

    How to validate an XML file with an XSD file

    Utlimately I want to be able to parse an xml STRING with an xsd STRING butthis is the best I could do: parsing an xml FILE with an xsd FILE. I basicallyreworked a console application example in the MSDN help file into a nicerlookingASP.NETWeb form example. It tells you if your file is not well-formedand then if it is not valid it lists out the specific reason (like in XMLSpy), quitehelpful to find an error in a large XMLfile as it returns the line number onwhich the error occurred as well as the tag name. This was done in VisualStudio.NETso to get it to work you will have to change the code around towhatever you want to do. Notice that you have to have the namespace in theroot element of the XML file.

    validate.aspx.cs

    using System;

    using System.Collections;

    using System.ComponentModel;

    using System.Data;

    using System.Drawing;

  • 8/7/2019 Applying XSLT to XML Using ASP

    9/12

    using System.Web;

    using System.Web.SessionState;

    using System.Web.UI;

    using System.Web.UI.WebControls;

    using System.Web.UI.HtmlControls;

    using System.IO;

    using System.Xml;

    using System.Xml.Schema;

    namespace validate

    {

    public class WebForm1 : System.Web.UI.Page

    {

    protected System.Web.UI.WebControls.Label Label1;

    protected System.Web.UI.WebControls.Button Button1;protected System.Web.UI.WebControls.Label Label3;

    protected System.Web.UI.WebControls.Label TheXml;

    protected System.Web.UI.WebControls.Label Label2;

    protected System.Web.UI.WebControls.Label Output;

    protected System.Web.UI.WebControls.Label Outcome;

    protected System.Web.UI.WebControls.Label TheXsd;

    private void Page_Load(object sender, System.EventArgs e)

    {

    //define variables

    TheXml.Text = HttpContext.Current.Server.MapPath("books.xml");

    TheXsd.Text = HttpContext.Current.Server.MapPath("books.xsd");

    Outcome.Text = "";

    }

    private void Button1_Click(object sender, System.EventArgs e)

    {

    //define variables

    Outcome.Text = "Succeeded";Output.Text = "";

    //load schema

    XmlSchemaCollection xsc = new XmlSchemaCollection();

    xsc.Add("generic", TheXsd.Text);

    Validate(TheXml.Text, xsc);

  • 8/7/2019 Applying XSLT to XML Using ASP

    10/12

    }

    private void Validate(String filename, XmlSchemaCollection xsc)

    {

    XmlTextReader reader = null;

    XmlValidatingReader vreader = null;

    reader = new XmlTextReader (filename);

    vreader = new XmlValidatingReader (reader);

    vreader.Schemas.Add(xsc);

    vreader.ValidationEventHandler += new ValidationEventHandler

    (ValidationCallBack);

    try

    {

    while (vreader.Read()){}}

    catch

    {

    Output.Text = "XML Document is not well-formed.";

    }

    vreader.Close();

    }

    public void ValidationCallBack (object sender, ValidationEventArgs args)

    {

    Outcome.Text = "Failed:";

    Output.Text += "Validation error: " + args.Message

    + "
    ";

    }

    }

    }

    Books.xml

    The Autobiography of Benjamin Franklin

  • 8/7/2019 Applying XSLT to XML Using ASP

    11/12

    Ben

    Franklin

    89.88

    The Confidence Man

    John

    Melville

    11.99

    Books.xsd

    ---------------------------

  • 8/7/2019 Applying XSLT to XML Using ASP

    12/12