The XML Server Control

   

The first thing to cover is the XML server control. This is located in the System.Web.UI.WebControls namespace and looks like the following:

 <asp:xml runat="server" /> 

As you can see, it is no different from any other server control in the way it is addressed. In inherits the Control object (as do all the other Web server controls), which provides it with all the base properties such as ID, EnableViewState, and Visible. If you need a refresher on all the properties it inherits from the Control object, refer back to Chapter 7 or the .NET Framework SDK. Table 13.1 looks at the additional properties that we'll be dealing with.

Table 13.1. XML Object Properties

Property

Description

Document

Gets or set the System.Xml.XmlDocument object to display in the XML control.

DocumentSource

Gets or sets the path to an XML document to display in the XML Control.

Transform

Gets or sets the System.Xml.Xsl.XslTransform object that formats the XML document's data for output to the browser.

TransformSource

Gets or sets the path to an XSLT (Extensible Stylesheet Language Transformations) document that formats the XML document before it is sent back to the web browser (usually as HTML or XHTML).

That all may seem like gobbledygook to you now. Let me explain as we progress and it will make a lot more sense. The first thing I'd like to do is give you the XML document that you'll see throughout all of the examples in this chapter.

products.xml
<?xml version="1.0"?>  <Products>      <Product>          <ProductID>1</ProductID>          <ProductName>Chai</ProductName>          <Supplier>Exotic Liquids</Supplier>          <CategoryName>Beverages</CategoryName>          <UnitPrice>18.23</UnitPrice>          <UnitsInStock>39</UnitsInStock>      </Product>      <Product>          <ProductID>2</ProductID>          <ProductName>Chang</ProductName>          <Supplier>Exotic Liquids</Supplier>          <CategoryName>Beverages</CategoryName>          <UnitPrice>19.02</UnitPrice>          <UnitsInStock>17</UnitsInStock>      </Product>      <Product>          <ProductID>24</ProductID>          <ProductName>Guarana Fantastica</ProductName>          <Supplier>Refrescos Americanas LTDA</Supplier>          <CategoryName>Beverages</CategoryName>          <UnitPrice>4.50</UnitPrice>          <UnitsInStock>20</UnitsInStock>      </Product>      <Product>          <ProductID>34</ProductID>          <ProductName>Sasquatch Ale</ProductName>          <Supplier>Bigfoot Breweries</Supplier>          <CategoryName>Beverages</CategoryName>          <UnitPrice>14.00</UnitPrice>          <UnitsInStock>111</UnitsInStock>      </Product>  </Products> 

This is an XML document that contains products from the Northwind database. Each product contains a ProductID, ProductName, Supplier, CategoryName, UnitPrice, and UnitsInStock. The XML server control is going to interact with this document in two ways: declaratively and programmatically.

Interacting with XML Declaratively

Internet Explorer 5 and later and Netscape 6 and later have the native capability to display XML documents. You can just request the XML document and the browser will render them. But when you're dealing with XML documents declaratively, you aren't just browsing the XML document; you are browsing to an ASP.NET page with an XML server control on that page. Then you use the DocumentSource and TransformSource properties to assign the XML and XSL documents to the XML server control.

DocumentSource and TransformSource

It's possible to just open an XML document in a browser, but here I'll explore the DocumentSource property to demonstrate what a raw XML file looks like in a browser (see Figure 13.1). Because I'm not using an XSL stylesheet, this document's ContentType must be equal to text/xml. Because this content type is XML, it will interpret any HTML tags as XML and actually render them to the browser. For this reason, the entire contents of our page are short and sweet.

Figure 13.1. Raw XML being rendered in the browser window.
graphics/13fig01.gif
Documentsource.xml
<%@ Page ContentType="text/xml" %>  <asp:xml  DocumentSource="products.xml" runat="server" /> 

When you set the DocumentSource property with a valid XML document, the XML server control renders the document to the browser. This utilization displays the XML document in the browser window. Utilitarian…yes! Pretty…no!!

Enter the XSL stylesheet, which is used to format XML documents. XSL stylesheets contain information and formatting for specific XML documents that describe how the information within the XML document should be rendered to the browser. This is done server-side and produces the desired result. This makes adding XML results to an HTML document possible, as well. The following file is the ASP.NET page that contains the XML server control.

xml_transformsource.aspx
<html>  <head>  <title>XML Style Sheet</title>  </head>  <body>  <asp:xml       DocumentSource="products.xml"      TransformSource="products.xsl"      runat="server" />  </body>  </html> 

Notice in the XML server control the two properties called DocumentSource and TransformSource. Again, the DocumentSource is the path to the XML file that will supply the data for the XML server control. The TransformSource property is used to set the path of the XSL stylesheet file that will provide formatting for the XML data in the DocumentSource property. Following is the XSL file.

products.xsl
<xsl:stylesheet version="1.0" xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>  <xsl:template match="/">      <style>      .table-heading {background-color:#CCCCCC;font-family : Verdana,sans-serif;font-size: graphics/ccc.gif12px;}      .table-row{font-family : Verdana,sans-serif;font-size:12px;}      </style>      <table border="1" cellpadding="3" cellspacing="0">      <tr >      <td>ProductID</td>      <td>Product Name</td>      <td>Supplier</td>      <td>Category</td>      <td>Unit Price</td>      <td>Units In Stock</td>      </tr>          <xsl:for-each select='Products/Product'>          <tr >              <td><xsl:value-of select='ProductID'/></td>              <td><xsl:value-of select='ProductName'/></td>              <td><xsl:value-of select='Supplier'/></td>              <td><xsl:value-of select='CategoryName'/></td>              <td><xsl:value-of select='UnitPrice'/></td>              <td><xsl:value-of select='UnitsInStock'/></td>              </tr>          </xsl:for-each>      </table>      </xsl:template>  </xsl:stylesheet> 

If you look at this XSL stylesheet, you will notice that it is made up primarily of familiar <html> tags. An XSL file is really just a formatting template for XML. First I inserted some CSS stylesheets to establish some text formatting for elements in the XSL file. It isn't necessary to include them in this file. They could have just as easily been in the ASP.NET page, but placing them in this file makes the XSL file totally modular.

Then I have created a <table> with a <tr> containing headings for the data contained in the XML file. Next is where the fun begins. I use the <xsl:for-each /> block to produce the code delimited by this tag for each Products/Product in the XML file. In other words, for each <Product> in <Products>, do blah, blah, blah.

Basically what this does is create a table row with table cells containing the elements contained inside the <Products> tag. Notice that I've assigned the CSS classes to both the table heading row and the product rows.

In Figure 13.2, you can see the results of running the xml_transformsource.aspx file. You can see how different the data appears than it did when I just displayed the raw XML. It is totally formatted by the XSL file that is declared in the TransformSource property of the XML server control.

Figure 13.2. XSL files provide formatting for XML data. You provide the path to the XSL file with the TransformSource property of the XML server control.
graphics/13fig02.gif

This is how you can declaratively use XML files in your ASP.NET applications, but what if you want to exert more control over XML integration? You can use programming logic in handling XML data as well.

Interacting with XML Programmatically

There are times when you need much more control in handling your XML documents. For instance, what if you want to view the contents of a document and then change its contents, such as by inserting new values?

This requires more control than simple properties can provide. The following is an example of displaying the contents of the products.xml file, but you can also insert items into the XML file. I use a few objects in this example that require that additional namespaces be imported.

System.Data is used because I utilize a DataSet and DataRow. The System.Xml namespace contains the XmlDocument and XmlNodeReader objects. I use these objects to hold and read the products.xml document into the DataSet. System.Xml.Xsl contains the XslTransform object, which holds the XSL file I'm programmatically using.

Visual Basic .NET xml_insert_vb.aspx
<%@ page language="vb" runat="server"%>  <%@ Import Namespace="System.Data"%>  <%@ Import Namespace="System.Xml"%>  <%@ Import Namespace="System.Xml.Xsl"%>  <script runat=server>  Private Sub Page_Load()      Dim OurXmlDocument As XmlDocument = New XmlDocument()      Dim OurXslTransform As XslTransform = New XslTransform()      OurXmlDocument.Load(Server.MapPath("products.xml"))      OurXslTransform.Load(Server.MapPath("products.xsl"))      OurXml.Transform = OurXslTransform      If IsPostBack Then          Dim OurDataSet As DataSet = New DataSet()          Dim OurXmlReader As XmlNodeReader = New XmlNodeReader(OurXmlDocument)          OurDataSet.ReadXml(OurXmlReader)          Dim OurDataRow As DataRow = OurDataSet.Tables("Product").NewRow()          OurDataRow("ProductID") = ProductID.Text          OurDataRow("ProductName") = ProductName.Text          OurDataRow("Supplier") = Supplier.Text          OurDataRow("CategoryName") = Category.Text          OurDataRow("UnitPrice") = UnitPrice.Text          OurDataRow("UnitsInStock") = UnitsInStock.Text          OurDataSet.Tables("Product").Rows.Add(OurDataRow)          OurDataSet.AcceptChanges()          OurDataSet.WriteXml(Server.MapPath("products.xml"))          Dim OurXmlDataDocument As XmlDataDocument = New XmlDataDocument(OurDataSet)            OurXml.Document = OurXmlDataDocument      Else          OurXml.Document = OurXmlDocument      End If  End Sub  </script>  <html>  <body>  <asp:xml  runat="server" EnableViewState="false"/>  <br>  <form runat="server">  <table>  <tr><td>ProductID</td>  <td><asp:TextBox  runat="server"/></td></tr>  <tr><td>Product Name</td>  <td><asp:TextBox  runat="server"/></td></tr>  <tr><td>Supplier</td>  <td><asp:TextBox  runat="server"/></td></tr>  <tr><td>Category</td>  <td><asp:TextBox  runat="server"/></td></tr>  <tr><td>Unit Price</td>  <td><asp:TextBox  runat="server"/></td></tr>  <tr><td>Units In Stock</td>  <td><asp:TextBox  runat="server"/></td></tr>  </table>  <asp:Button  text="Submit" runat="server"/>  </form>  </body>  </html> 
C# xml_insert_cs.aspx
<%@ page language="c#" runat="server"%>  <%@ Import Namespace="System.Data"%>  <%@ Import Namespace="System.Xml"%>  <%@ Import Namespace="System.Xml.Xsl"%>  <script runat=server>  void Page_Load() {     XmlDocument OurXmlDocument = new XmlDocument();      XslTransform OurXslTransform = new XslTransform();      OurXmlDocument.Load(Server.MapPath("products.xml"));      OurXslTransform.Load(Server.MapPath("products.xsl"));      OurXml.Transform = OurXslTransform;      if (IsPostBack) {          DataSet OurDataSet = new DataSet();          XmlNodeReader OurXmlReader = new XmlNodeReader(OurXmlDocument);          OurDataSet.ReadXml(OurXmlReader);          DataRow OurDataRow = OurDataSet.Tables["Product"].NewRow();          OurDataRow["ProductID"] = ProductID.Text;          OurDataRow["ProductName"] = ProductName.Text;          OurDataRow["Supplier"] = Supplier.Text;          OurDataRow["CategoryName"] = Category.Text;          OurDataRow["UnitPrice"] = UnitPrice.Text;          OurDataRow["UnitsInStock"] = UnitsInStock.Text;          OurDataSet.Tables["Product"].Rows.Add(OurDataRow);          OurDataSet.AcceptChanges();          OurDataSet.WriteXml(Server.MapPath("products.xml"));          XmlDataDocument OurXmlDataDocument = new XmlDataDocument(OurDataSet);          OurXml.Document = OurXmlDataDocument;      }      else {          OurXml.Document = OurXmlDocument;      }  }  </script>  <html>  <body>  <asp:xml  runat="server" EnableViewState="false"/>  <br>  <form runat="server">  <table>  <tr><td>ProductID</td>  <td><asp:TextBox  runat="server"/></td></tr>  <tr><td>Product Name</td>  <td><asp:TextBox  runat="server"/></td></tr>  <tr><td>Supplier</td>  <td><asp:TextBox  runat="server"/></td></tr>  <tr><td>Category</td>  <td><asp:TextBox  runat="server"/></td></tr>  <tr><td>Unit Price</td>  <td><asp:TextBox  runat="server"/></td></tr>  <tr><td>Units In Stock</td>  <td><asp:TextBox  runat="server"/></td></tr>  </table>  <asp:Button  text="Submit" runat="server"/>  </form>  </body>  </html> 

To give you an idea what happens in the highlighted text, first I create a new XmlDocument object and an XslTransform object. Both these objects have a load method that takes a parameter of the file path to the document that you want to load into them. I used the Server.MapPath() method, which returns the filename in the MapPath parameter and builds the full path to that object, starting from the drive letter forward. This is passed into the XmlDocument and XslTransform objects' Load methods to fill those objects with the XML and XSL files that I want, which is products.xml and products.xsl.

Then I set OurXml's transform property to the value of the XmlTransform object. OurXml is the XML server control in the ASP.NET page.

Then I check to see whether the page is posting back to itself. If it does, then I create a DataSet, create an XmlNodeReader object, and populate it with the XmlDocument object. The XmlNodeReader allows the DataSet's ReadXml method to properly create a DataTable of the contents of the XML document.

After the XmlDocument object is in the DataSet, I create a new DataRow based on the DataTable created by the DataSet's ReadXml method. If fill the DataRow with the values from the TextBox server controls and then use the Add() method to add the DataRow to the Products DataTable in the DataSet and accept the changes with the AcceptChanges() method.

Next, I use the WriteXml() counterpart of the DataSet's ReadXml() method, and write the contents of the DataSet back to the products.xml file.

I then place the contents of the DataSet into an XmlDataDocument, which is an object that allows data to be stored, retrieved, and manipulated through a DataSet, and I set the Document property of the OurXml server control to this object.

If the page hasn't been posted back, it simply uses the XmlDocument object to populate OurXml server control's Document property.

You can see in Figure 13.3 that the values in the edit boxes were added to the table. In theory this means they were added to the XML file.

Figure 13.3. When manipulating XML files you can programmatically do just about anything to them that you can do to a database, including inserting data.
graphics/13fig03.gif
products.xml
<?xml version="1.0" standalone="yes"?>  <Products>    <Product>      <ProductID>1</ProductID>      <ProductName>Chai</ProductName>      <Supplier>Exotic Liquids</Supplier>      <CategoryName>Beverages</CategoryName>      <UnitPrice>18.23</UnitPrice>      <UnitsInStock>39</UnitsInStock>    </Product>    <Product>      <ProductID>2</ProductID>      <ProductName>Chang</ProductName>      <Supplier>Exotic Liquids</Supplier>      <CategoryName>Beverages</CategoryName>      <UnitPrice>19.02</UnitPrice>      <UnitsInStock>17</UnitsInStock>    </Product>    <Product>      <ProductID>24</ProductID>      <ProductName>Guarana Fantastica</ProductName>      <Supplier>Refrescos Americanas LTDA</Supplier>      <CategoryName>Beverages</CategoryName>      <UnitPrice>4.50</UnitPrice>      <UnitsInStock>20</UnitsInStock>    </Product>    <Product>      <ProductID>34</ProductID>      <ProductName>Sasquatch Ale</ProductName>      <Supplier>Bigfoot Breweries</Supplier>      <CategoryName>Beverages</CategoryName>      <UnitPrice>14.00</UnitPrice>      <UnitsInStock>111</UnitsInStock>    </Product>    <Product>      <ProductID>60</ProductID>      <ProductName>Brewed Tea</ProductName>      <Supplier>Peter</Supplier>      <CategoryName>Beverages</CategoryName>      <UnitPrice>6.25</UnitPrice>      <UnitsInStock>20</UnitsInStock>    </Product>  </Products> 

You can see at the bottom of the products.xml file that the information that I inserted into the TextBox server controls has been properly written to the products.xml document.

That is one way of using a DataSet and its ReadXml() and WriteXml() methods to manipulate the product.xml file. There are also objects within the System.Xml namespace that enable you to do the same thing that I did with the DataSet but do it directly to the XML file.

In the following example, if the page is posted back, I use the XmlElement object to build a whole bunch of XML tags. I fill the appropriate XmlElements with the contents of the TextBox server controls. I then append them as children to the one XmlElement object that is named xmlProduct. I then place that in the XML document using the XmlNode object's AppendChild() method and then save the XML document back. It's just another way of doing the same thing, this time with XML and XML objects.

Visual Basic .NET xml_insert_purexml_vb.aspx
<%@ page language="vb" runat="server"%>  <%@ Import Namespace="System.Data"%>  <%@ Import Namespace="System.Xml"%>  <%@ Import Namespace="System.Xml.Xsl"%>  <script runat=server>  Private Sub Page_Load()      Dim OurXmlDocument As XmlDocument = New XmlDocument()      Dim OurXslTransform As XslTransform = New XslTransform()      OurXmlDocument.Load(Server.MapPath("products.xml"))      OurXslTransform.Load(Server.MapPath("products.xsl"))      If IsPostBack Then          Dim OurXmlNode As XmlNode = OurXmlDocument.DocumentElement          Dim xmlProduct As XmlElement = OurXmlDocument.CreateElement("Product")          Dim xmlProductID As XmlElement = OurXmlDocument.CreateElement("ProductID")          Dim xmlProductName As XmlElement = OurXmlDocument.CreateElement("ProductName")          Dim xmlSupplier As XmlElement = OurXmlDocument.CreateElement("Supplier")          Dim xmlCategoryName As XmlElement = OurXmlDocument.CreateElement("CategoryName")          Dim xmlUnitPrice As XmlElement = OurXmlDocument.CreateElement("UnitPrice")          Dim xmlUnitsInStock As XmlElement = OurXmlDocument.CreateElement("UnitsInStock")          xmlProductID.InnerXml = ProductID.Text          xmlProductName.InnerXml = ProductName.Text          xmlSupplier.InnerXml = Supplier.Text          xmlCategoryName.InnerXml = Category.Text          xmlUnitPrice.InnerXml = UnitPrice.Text          xmlUnitsInStock.InnerXml = UnitsInStock.Text          xmlProduct.AppendChild(xmlProductID)          xmlProduct.AppendChild(xmlProductName)          xmlProduct.AppendChild(xmlSupplier)          xmlProduct.AppendChild(xmlCategoryName)          xmlProduct.AppendChild(xmlUnitPrice)          xmlProduct.AppendChild(xmlUnitsInStock)          OurXmlNode.AppendChild(xmlProduct)          OurXmlDocument.Save(Server.MapPath("products.xml"))      End If      OurXml.Transform = OurXslTransform      OurXml.Document = OurXmlDocument  End Sub  </script>  <html>  <body>  <asp:xml  runat="server" EnableViewState="false"/>  <br>  <form runat="server">  <table>  <tr><td>ProductID</td>  <td><asp:TextBox  runat="server"/></td></tr>  <tr><td>Product Name</td>  <td><asp:TextBox  runat="server"/></td></tr>  <tr><td>Supplier</td>  <td><asp:TextBox  runat="server"/></td></tr>  <tr><td>Category</td>  <td><asp:TextBox  runat="server"/></td></tr>  <tr><td>Unit Price</td>  <td><asp:TextBox  runat="server"/></td></tr>  <tr><td>Units In Stock</td>  <td><asp:TextBox  runat="server"/></td></tr>  </table>  <asp:Button  text="Submit" runat="server"/>  </form>  </body>  </html> 
C# xml_insert_purexml_cs.aspx
<%@ page language="c#" runat="server"%>  <%@ Import Namespace="System.Data"%>  <%@ Import Namespace="System.Xml"%>  <%@ Import Namespace="System.Xml.Xsl"%>  <script runat=server>  void Page_Load() {     XmlDocument OurXmlDocument = new XmlDocument();      XslTransform OurXslTransform = new XslTransform();      OurXmlDocument.Load(Server.MapPath("products.xml"));      OurXslTransform.Load(Server.MapPath("products.xsl"));      if (IsPostBack) {            XmlNode OurXmlNode = OurXmlDocument.DocumentElement;          XmlElement xmlProduct = OurXmlDocument.CreateElement("Product");          XmlElement xmlProductID = OurXmlDocument.CreateElement("ProductID");          XmlElement xmlProductName = OurXmlDocument.CreateElement("ProductName");          XmlElement xmlSupplier = OurXmlDocument.CreateElement("Supplier");          XmlElement xmlCategoryName = OurXmlDocument.CreateElement("CategoryName");          XmlElement xmlUnitPrice = OurXmlDocument.CreateElement("UnitPrice");          XmlElement xmlUnitsInStock = OurXmlDocument.CreateElement("UnitsInStock");          xmlProductID.InnerXml = ProductID.Text;          xmlProductName.InnerXml = ProductName.Text;          xmlSupplier.InnerXml = Supplier.Text;          xmlCategoryName.InnerXml = Category.Text;          xmlUnitPrice.InnerXml = UnitPrice.Text;          xmlUnitsInStock.InnerXml = UnitsInStock.Text;          xmlProduct.AppendChild(xmlProductID);          xmlProduct.AppendChild(xmlProductName);          xmlProduct.AppendChild(xmlSupplier);          xmlProduct.AppendChild(xmlCategoryName);          xmlProduct.AppendChild(xmlUnitPrice);          xmlProduct.AppendChild(xmlUnitsInStock);          OurXmlNode.AppendChild(xmlProduct);          OurXmlDocument.Save(Server.MapPath("products.xml"));      }      OurXml.Transform = OurXslTransform;      OurXml.Document = OurXmlDocument;  }  </script>  <html>  <body>  <asp:xml  runat="server" EnableViewState="false"/>  <br>  <form runat="server">  <table>  <tr><td>ProductID</td>  <td><asp:TextBox  runat="server"/></td></tr>  <tr><td>Product Name</td>  <td><asp:TextBox  runat="server"/></td></tr>  <tr><td>Supplier</td>  <td><asp:TextBox  runat="server"/></td></tr>  <tr><td>Category</td>  <td><asp:TextBox  runat="server"/></td></tr>  <tr><td>Unit Price</td>  <td><asp:TextBox  runat="server"/></td></tr>  <tr><td>Units In Stock</td>  <td><asp:TextBox  runat="server"/></td></tr>  </table>  <asp:Button  text="Submit" runat="server"/>  </form>  </body>  </html> 

This just demonstrates the flexibility that the .NET Framework provides for dealing with XML documents. There are many other objects that will help you to play around with XML documents, and I would encourage you to investigate the System.XML namespace and all its objects to further understand how you can use XML in your ASP.NET applications.

One Little Bonus

As a small bonus, I thought it would be fun to show you how to populate a DataSet with two tables and apply an XSL stylesheet that can handle the formatting of both tables in the DataSet.

Visual Basic .NET xml_bonus_vb.aspx
<%@ page language="vb" runat="server"%>  <%@ Import Namespace="System.Data"%>  <%@ Import Namespace="System.Data.SqlClient"%>  <%@ Import Namespace="System.Xml"%>  <%@ Import Namespace="System.Xml.Xsl"%>  <script runat=server>  Private Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)      Dim OurConnection As SqlConnection = New SqlConnection("Server=server;uid=newriders; graphics/ccc.gifpwd=password;database=Northwind")      Dim OurCommand As SqlCommand = New SqlCommand()      OurCommand.Connection = OurConnection      Dim OurDataAdapter As SqlDataAdapter = New SqlDataAdapter()      Dim OurDataSet As DataSet      OurDataSet = New DataSet("OurDataSet")      OurCommand.CommandText = "Select Top 10 p.ProductID, p.ProductName, s.CompanyName as  graphics/ccc.gifSupplier, c.CategoryName, UnitPrice, UnitsInStock From Products p, Categories c,  graphics/ccc.gifSuppliers s Where p.CategoryID = c.CategoryID and p.SupplierID = s.SupplierID"      OurDataAdapter.SelectCommand = OurCommand      OurDataAdapter.Fill(OurDataSet, "Products")      OurCommand.CommandText = "Select Top 10 Title, TitleOfCourtesy, FirstName, LastName,  graphics/ccc.gifAddress, City From Employees"      OurDataAdapter.Fill(OurDataSet, "Employees")      Dim OurXmlDocument As XmlDataDocument = New XmlDataDocument(OurDataSet)      OurXml.Document = OurXmlDocument  End Sub  </script>  <html>  <head>  <title>XML Bonus</title>  </head>  <body bgcolor="#FFFFFF" text="#000000"  <asp:xml  TransformSource="bonus.xsl" runat="server" />  </body>  </html> 
C# xml_bonus_cs.aspx
<%@ page language="c#" runat="server"%>  <%@ Import Namespace="System.Data"%>  <%@ Import Namespace="System.Data.SqlClient"%>  <%@ Import Namespace="System.Xml"%>  <%@ Import Namespace="System.Xml.Xsl"%>  <script runat=server>  void Page_Load(Object sender, EventArgs e) {      SqlConnection OurConnection = new SqlConnection("Server=server;uid=newriders; graphics/ccc.gifpwd=password;database=Northwind");      SqlCommand OurCommand = new SqlCommand();      OurCommand.Connection = OurConnection;      SqlDataAdapter OurDataAdapter = new SqlDataAdapter();      DataSet OurDataSet;      OurDataSet = new DataSet("OurDataSet");      OurCommand.CommandText = "Select Top 5 p.ProductID, p.ProductName, s.CompanyName as  graphics/ccc.gifSupplier, c.CategoryName, UnitPrice, UnitsInStock From Products p, Categories c,  graphics/ccc.gifSuppliers s Where p.CategoryID = c.CategoryID and p.SupplierID = s.SupplierID";      OurDataAdapter.SelectCommand = OurCommand;      OurDataAdapter.Fill(OurDataSet, "Products");      OurCommand.CommandText = "Select Top 5 Title, TitleOfCourtesy, FirstName, LastName,  graphics/ccc.gifAddress, City From Employees";      OurDataAdapter.Fill(OurDataSet, "Employees");      XmlDataDocument OurXmlDocument = new XmlDataDocument(OurDataSet);      OurXml.Document = OurXmlDocument;  }  </script>  <html>  <head>  <title>XML Bonus</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <asp:xml  TransformSource="bonus.xsl" runat="server" />  </body>  </html> 

This ASP.NET page creates a DataSet, and then pulls data from two different tables in the SQL Server Northwind database and places it into two DataTables: Products and Employees.

Then I take the DataSet and place it in an XmlDataDocument object and set the Document property of the XML server control to the contents of the XmlDataDocument. Basically there are two different tables going into the OurXml server control.

Now you apply two different styles to the two different tables. For this we just create an XSL file. In the above ASP.NET page it was assigned to the TransformSource property of the XML server control and is named bonus.xsl.

bonus.xsl
<xsl:stylesheet version="1.0" xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>  <xsl:template match="/">  <style>  .table-heading {background-color:#CCCCCC;font-family : Verdana,sans-serif;font-size:12px; graphics/ccc.gif}  .table-row{font-family : Verdana,sans-serif;font-size:12px;}  </style>  <table border="1" cellpadding="3" cellspacing="0">  <tr >  <td>ProductID</td>  <td>Product Name</td>  <td>Supplier</td>  <td>Category</td>  <td>Unit Price</td>  <td>Units In Stock</td>  </tr>  <xsl:for-each select='OurDataSet/Products'>  <tr >  <td><xsl:value-of select='ProductID'/></td>  <td><xsl:value-of select='ProductName'/></td>  <td><xsl:value-of select='Supplier'/></td>  <td><xsl:value-of select='CategoryName'/></td>  <td><xsl:value-of select='UnitPrice'/></td>  <td><xsl:value-of select='UnitsInStock'/></td>  </tr>  </xsl:for-each>  </table>  <br /><br />  <table border="1" cellpadding="3" cellspacing="0">  <tr >  <td>Title</td>  <td>Title Of Courtesy</td>  <td>First Name</td>  <td>Last Name</td>  <td>Address</td>  <td>City</td>  </tr>  <xsl:for-each select='OurDataSet/Employees'>  <tr >  <td><xsl:value-of select='Title'/></td>  <td><xsl:value-of select='TitleOfCourtesy'/></td>  <td><xsl:value-of select='FirstName'/></td>  <td><xsl:value-of select='LastName'/></td>  <td><xsl:value-of select='Address'/></td>  <td><xsl:value-of select='City'/></td>  </tr>  </xsl:for-each>  </table>  </xsl:template>  </xsl:stylesheet> 

The real magic happens when I set the select attribute of the <xml:for-each> tag. You can see the first highlighted group is set to select='OurDataSet/Products'. This causes that portion of the XSL file to use the data stored in the Products table of OurDataSet.

The second highlighted group is set to select='OurDataSet/Employees', and this subsequently causes that portion of the XSL file to use the data stored in the Employees table of OurDataSet.

As you can see in Figure 13.4, the XML server control uses the bonus.xsl stylesheet to format the two different tables from the DataSet that were transformed into XML using the XmlDataDocument object. These two different tables receive two different formattings based on which data was assigned to the select attribute of the <xml:for-each> tag.

Figure 13.4. XML and XSL provide lots of flexibility for handling data, and the XML server control provides a tool to use these files in your ASP.NET applications.
graphics/13fig04.gif

This bonus was intended to show you the flexibility of the XML server control and the versatility of using XSL files to format your XML data. Experiment, have fun, and get used to XML data, because you will be seeing more and more of it as time progresses and XML is adopted to do more things in web development and web applications.

One thing to note is that throughout this chapter I used XML files as the source for the examples, but in real-world situations XML data is more commonly delivered out of a database than an XML file. Considering this, along with the fact that volumes have been written about XML, I will state that I have hardly scratched the surface on this subject. I highly encourage you to explore the web and other books concerning ASP.NET and XML, especially in the area of web services. The following are some additional recommendations of titles covering this area:

  • XML and ASP.NET by Kirk Evans, Ashwin Kamanna, and Joel Mueller.

    Published by New Riders Publishing.

  • XML and SQL Server 2000 by John Griffin.

    Published by New Riders Publishing.

  • Inside XML by Steve Holzner.

    Published by New Riders Publishing.


   
Top


ASP. NET for Web Designers
ASP.NET for Web Designers
ISBN: 073571262X
EAN: 2147483647
Year: 2005
Pages: 94
Authors: Peter Ladka

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net