
C# ПІДРУЧНИКИ / c# / Hungry Minds - ASP.NET Bible VB.NET & C#
.pdf
<HTML>
<HEAD> <TITLE> Items Data </TITLE> </HEAD>
<BODY>
<OL>
<LI> Item Name : Chocolate Price: 1 </LI>
<LI> Item Name: Cadbury Price: 2.5 </LI>
</OL>
</BODY>
</HTML>
When you open this HTML document in a browser, such as Internet Explorer 5.0, it will look like Figure 13-1.
Figure 13-1: An HTML document
Now, let's create an XML document that represents the same information:
<?xml version="1.0"?>
<ITEMS>
<ITEM>
<NAME> Chocolate </NAME>
<PRICE> 1 </PRICE>
</ITEM>
<ITEM>
<NAME> Cadbury </NAME>
<PRICE> 2.5 </PRICE>
</ITEM>
</ITEMS>
In this code, the first statement, <?xml version="1.0"?>, is called XML declaration. It informs the browser that the document being processed is an XML document.
Note XML documents have the extension .xml.
When you open the preceding XML document in Internet Explorer 5.0, it will look like Figure 13-2.

Figure 13-2: An XML document
As can be seen from the figure, the XML document is displayed in the form of a tree view, which can be expanded and collapsed. Any XML document that you open in Internet Explorer 5.0 will be displayed in a similar format.
While creating an XML document, you must remember some basic rules:
§All tags must be closed. In HTML, even if you don't close a tag, it does not give you any errors. However, in XML, all opening tags must have corresponding closing tags; otherwise, the browser displays an error message.
§All empty tags must include a / character before the closing angular bracket
(>). For example, in HTML, you have the <IMG> tag for inserting an image in a Web page. This tag does not require any closing tag because the tag
itself contains all the relevant information, such as the image source and its position. Therefore, <IMG> is an empty tag. If you want to use an empty tag called <Image> in XML, you must include a / character before closing the angular bracket of the tag as follows:
<Image src="tree.gif" />
§All attributes of an element must be enclosed within quotes.
§Tags should not overlap; that is, the innermost tag must be closed before closing the outer tags. Consider the following code:
<FirstName> James <LastName> Ford </FirstName> </LastName>
This statement would result in an error because the outer tag, <FirstName>, has been closed before the inner tag, <LastName>.
§Tags are case-sensitive. Therefore, the case of the closing tag should match the case used in the opening tag.
An XML document that conforms to these rules is called a well-formed XML document.
An Overview of XML-Related Specifications
XML does not exist all by itself. Numerous additional XML-related specifications provide guidelines for working with XML documents. Before discussing the implementation of XML in ASP.NET, it is important to understand these XML-related specifications. Therefore, this section looks at some of the important XML-related W3C specifications.
Document Type Definition
A Document Type Definition (DTD) enables you to specify the structure of the content in an XML document. Creating a DTD is similar to using a CREATE TABLE statement in SQL, in which you specify the columns to be included in the table and whether they can hold null values. In a DTD, you can specify the elements that can be used in an XML document and specify whether it is mandatory to provide values for the elements.
When you include a DTD in an XML document, software checks the structure of the XML document against the DTD. This process of checking the structure of the XML document
is called validating. The software that performs the task of validating is called a parser. The following are the two types of parsers:
§Nonvalidating parser: Checks whether an XML document is well formed. An example of a nonvalidating parser is the expat parser.
§Validating parser: Checks whether an XML document is well formed
and whether it conforms to the DTD that it uses. The MSXML parser provided with Microsoft Internet Explorer 5.0 is an example of a validating parser.
An XML document that conforms to the DTD is called a valid document.
An example of a DTD is given as follows:
<!ELEMENT ITEMS (ITEM)+>
<!ELEMENT ITEM (NAME, PRICE)>
<!ELEMENT NAME (#PCDATA)>
<!ELEMENT PRICE (#PCDATA)>
In this example, we have declared four elements, ITEMS, ITEM, NAME, and PRICE. After specifying the element name, you specify the type of content of that element. In case of ITEMS, the content type is (ITEM)+, which means that this element can contain one or more ITEM elements. Similarly, the ITEM element contains the elements NAME and PRICE, which contain character data. This type of data is represented as (#PCDATA).
Note DTD files have the extension .dtd.
You can attach this DTD to an XML document by including the following statement after the processing instruction:
<!DOCTYPE ITEMS SYSTEM "items.dtd">
Consider the following XML document that uses the previous DTD statement:
<?xml version="1.0"?>
<!DOCTYPE ITEMS SYSTEM "ITEMS.DTD">
<ITEMS>
<ITEM>
<NAME> Chocolate </NAME>
</ITEM>
</ITEMS>
When you check this document using a validating parser such as MSXML, it results in an error message, because the ITEM element declared in the DTD contains two mandatory elements, NAME and PRICE. However, the PRICE element is missing in the XML document. Thus, a DTD enables you to implement consistency in the structure of data contained within XML documents.
XML namespaces
As stated earlier, XML enables you to create your own elements. It also enables you to use elements that are defined for and used by various software modules. This may lead to certain problems. For example, in case of a purchase order, you may have an element called QTY that stores the quantity of a purchase. In some other case, the same element may be used to store the quantity on hand for a particular item. In such a case, there may be a collision of elements having the same names. To prevent this from happening, W3C has recommended the use of XML namespaces.
XML namespaces use Uniform Resource Identifiers (URIs) to differentiate tags used in different vocabularies. With this approach, each element can be uniquely identified using the namespace. A namespace can be declared using the xmlns keyword. For example, a namespace for a purchase order could be defined in the following way:
xmlns:PurchaseOrder="http://www.po.com/po"
Now when you use the QTY element, you must prefix it with the alias "PurchaseOrder" as follows:
<PurchaseOrder:QTY>
When you specify a namespace URI, the parser does not actually search for the URI, nor does it search for any documents at the specified URI. The URI just serves as a unique identifier for tags from different vocabularies.
XML schemas
An XML schema provides a way of defining a structure of an XML document. It enables you to describe the elements and attributes that can be present in an XML document. An XML schema is similar to a DTD. However, it can be considered a superset of a DTD in terms of the functionality that it provides. An advantage of using an XML schema is that it enables you to specify the data types for elements. A DTD, on the other hand, enables you to specify whether the element can contain character data or other elements, or whether it is an empty element. It does not enable you to specify whether a particular element should contain integer, float, or string values. Another difference between an XML schema and a DTD is that an XML schema follows XML syntax. In other words, it is an application of XML, whereas a DTD has its own syntax.
The following is an example of an XML schema for the Items.xml document:
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<!-- Declaring the root element "ITEMS" --> <xsd:element name="ITEMS" type="ITEMDATA"/>
<!-- Declaring the complex type "ITEMSDATA" which should contain one or more "ITEM" elements -->
<xsd:complexType name="ITEMDATA"> <xsd:sequence>
<!-- The "ITEM" element can occur one or more times in
the XML document. This can be specified by using the minOccurs and maxOccurs
attributes -->
<xsd:element name="ITEM" type="DETAILS" minOccurs="0"
maxOccurs="unbounded" />
</xsd:sequence>
</xsd:complexType>
<!-- Declaring the complex type "DETAILS" which is used in the
"ITEM" element. This type contains the elements "NAME" and "PRICE" -->
<xsd:complexType name="DETAILS">
<xsd:sequence>
<xsd:element name="NAME" type="xsd:string"/>
<xsd:element name="PRICE" type="xsd:decimal" />
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
As you can see from this example, you can specify the structure of elements by using an XML schema. In addition, you can specify whether the element occurs once or more
than once, whether it is optional, and whether it should contain a string or a numeric value. When you validate an XML document against this schema, the parser will ensure that all the necessary elements are specified in the XML document. In addition, it will check whether the value specified in the PRICE element is a numeric value. If you add a string instead of a numeric value, the parser will give you an error message. Thus, XML schemas provide additional control over the contents in an XML document, as compared to a DTD.
Note
Extensible Stylesheet Language Transformations (XSL/T)
As discussed earlier, XML does not deal with the presentation of data contained within an XML document. It concentrates only on the structure and the data contained within the structure. This separation of the data and its presentation enables you to display the same data in various formats. However, because an XML document does not contain any formatting instructions for displaying data, you need some special tool that can convert an XML document into a user-viewable format.
XSL/T is a W3C specification for formatting XML documents and displaying them in the desired format. XSL/T follows XML syntax. You will be looking at the creation of an XSL/T style sheet later in this chapter in the section "XML Web server control."
XML Document Object Model
The XML Document Object Model (XML DOM) is an in-memory representation of an XML document. It represents data in the form of hierarchically organized object nodes, and enables you to programmatically access and manipulate the elements and attributes present in an XML document. W3C has provided some common DOM interfaces for accessing XML documents through a program. These standard interfaces have been implemented in different ways. Microsoft's implementation of XML DOM has the XMLDocument class, which is at the top of the document object hierarchy. It represents the complete XML document. Another example is the XMLTransform class, which has a reference to the XSL/T file that specifies how the XML data is to be transformed. You can access XML DOM classes and objects from any scripting language as well as from programming languages such as VB.NET.
Support for XML in ASP.NET
The growing popularity of XML as a common data interchange format between Web applications has resulted in an increase in the number of software platforms that support XML, and ASP.NET is no exception. ASP.NET enables you to work with XML by supporting a number of XML-related classes. Some of the features provided in ASP.NET for working with XML are as follows:
§System.Xml namespace
§XML server-side control
§Data conversion from a relational to XML format
§Data binding with XML documents
System.Xml namespace
The System.Xml namespace is a collection of classes that are used to process an XML document. This namespace supports XML-related specifications, such as DTDs, XML schemas, XML namespaces, XML DOM, and XSL/T. Some of the classes present in the System.Xml namespace are as follows:
§XmlDocument: Represents a complete XML document.
§XmlDataDocument: Derived from the XmlDocument class and enables you to store and manipulate XML and relational data into a data set.
§XmlElement: Represents a single element from an XML document.
§XmlAttribute: Represents a single attribute of an element.
§XmlDocumentType: Represents the DTD used by an XML document.
§XmlTextReader: Represents a reader that performs a fast, noncached, forward-only read operation on an XML document.
§XmlTextWriter: Represents a writer that performs a fast, noncached, forward-only generation of streams and files that contain XML data.
XML Web server control
The XML Web server control enables you to insert an XML document as a control within a Web Form. The control has the following properties:
§DocumentSource: Enables you to specify the URL to the XML document to be displayed in the Web form
§TransformSource: Enables you to specify the URL to the XSL/T file, which transforms the XML document into a desired format before it is displayed in the Web form
§Document: Enables you to specify a reference to an object of the XMLDocument class
§Transform: Enables you to specify a reference to an object of the XMLTransform class
All four properties can be changed programmatically by providing an ID to the XML server-side control. To use the XML server-side control in ASP.NET, you can use the following syntax:
<asp:xml DocumentSource="XML document" TransformSource=
"XSL/T file" Document="XMLDocument object" Transform="XSLTransform object">
You can also use the toolbox to create an XML Web server control. You can drag the XML control from the Web Forms tab and then set the DocumentSource, TransformSource, Document, and Transform properties of the control.
Consider the following XML document:
<?xml version = "1.0"?>
<Products>
<Product>
<ProductId> P001 </ProductId>
<ProductName> Baby Food </ProductName>
<UnitPrice> 2.5 </UnitPrice>
<QtyAvailable> 1200 </QtyAvailable>
</Product>
<Product>
<ProductId> P002 </ProductId>
<ProductName> Chocolate </ProductName>
<UnitPrice> 1.5 </UnitPrice>
<QtyAvailable> 1500 </QtyAvailable>
</Product>
</Products>
You can transform this XML document into a desired format by creating a style sheet. The steps for creating an XSL/T style sheet are as follows:
1.XSL/T follows XML syntax. Therefore, the following is the first line in the XSL/T file:
<?xml version="1.0"?>
2.An XSL/T file has stylesheet as its root element. This element also specifies the namespace for XSL/T:
3.<xsl:stylesheet version = "1.0" xmlns:xsl =
"http://www.w3.org/1999/XSL/Transform">
The XSL/T processor provided with the MSXML parser supports the URI "http://www.w3.org/1999/XSL/Transform" for XSL/T.
4.Create a template for displaying your data in the desired format. You can create a template using the template element. The match attribute of the template element enables you to specify the element from which you want the template to be applied. If you want to apply the template from the root element, you provide the value "/" to the match attribute:
<xsl:template match="/">
5.Within the template, you can use HTML tags to create an ordered list:
6.<OL>
7.The data from the XML document should be fetched and displayed in the ordered list. All data from the XML document needs to be processed. You use the for-each element to perform a task repeatedly. The select attribute of the for-each element enables you to specify the element for which the repetitive task needs to be performed. In this example, each product needs to be processed. The "Product" element exists within the "Products" element. Therefore, you give the following statement to process the details of each product:
<xsl:for-each select='Products/Product'>
8.Next, you need to fetch the values of various elements within the "Product" element and display the values in the list. You can fetch the values of elements from an XML document using the value-of element. The select attribute of the value-of element enables you to specify the element that needs to be fetched. The following code snippet shows how values for each product can be fetched and displayed in the list:
9.<LI>
10.<b><i>
11. |
Product Id : |
12. <xsl:value-of select='ProductId'/> <br />
13.</i></b>
14.Product Name :
15. <xsl:value-of select='ProductName'/> <br />
16.Unit Price :
17. <xsl:value-of select='UnitPrice'/> <br />
18.Quantity On Hand :
19. <xsl:value-of select='QtyAvailable'/> <br />
20.<hr />
</LI>
In this code, the <LI> tag of HTML is used to create a list item. The <BR> tag is used to insert a line break. Note that the <BR> tag has an extra / character before the closing angular bracket. Because XSL/T follows XML syntax, you must ensure that all empty elements have the / character.
21.The last step is to ensure that all the opening tags are closed:
22.</xsl:for-each>
23.</OL>
24. </xsl:template> </xsl:stylesheet>
The complete XSL/T style sheet will look as follows: <?xml version="1.0"?>
<xsl:stylesheet version = "1.0" xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/"> <OL>
<xsl:for-each select='Products/Product'> <LI>
<b> <i> Product Id :
<xsl:value-of select='ProductId'/> <br /> </i></b>
Product Name :
<xsl:value-of select='ProductName'/> <br /> Unit Price :
<xsl:value-of select='UnitPrice'/> <br /> Quantity On Hand :
<xsl:value-of select='QtyAvailable'/> <br /> <hr />
</LI> </xsl:for-each>
</OL>
</xsl:template>
</xsl:stylesheet>
You can display the formatted XML document in a Web form by typing the following code in an ASPX file:
<html>
<body>
<asp:xml id="MyXmlDoc" documentsource="products.xml" transformsource="products.xsl" runat="server">
</asp:xml>
</body>
</html>
When you execute the application, it will give the output shown in Figure 13-3.

Figure 13-3: Output of the application implementing the XML server-side control
Converting Relational Data to XML Format
ASP.NET enables you to easily convert the data from a database into an XML document. ASP.NET provides the XMLDataDocument class, which enables you to load relational data as well as data from an XML document into a data set. The data loaded in XMLDataDocument can then be manipulated using the W3C Document Object Model.
The following example converts the data stored in the "Orders" table of the "Sales" database on SQL Server 7.0 into an XML document:
<%@ Page ContentType="text/xml" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Xml" %>
<script language="VB" runat=server>
Sub Page_Load(Sender as Object, E as EventArgs)
Dim SQLcon as New SqlConnection (
"server=localhost;uid=sa;pwd=; |
database= sales") |
|
Dim Mycommand as New SqlDataAdapter |
||
("SELECT * FROM |
Orders", SQLCon) |
Dim dsOrders As New DataSet()
Mycommand.Fill(dsOrders, "Order")
Dim XmlDoc as XmlDocument = New
XmlDataDocument(dsOrders)
MyXmlDoc.Document = XmlDoc
Xmldoc.save ("orders.xml")
End Sub
</script>
<asp:xml id="MyXmlDoc" runat=server/>
In this example, you specify that the contents of the page represent an XML document by giving the following statement:
<%@ Page ContentType="text/xml" %>
You can also set the ContentType property to HTML to indicate that the page contains HTML elements. This statement is given to ensure that the contents of the resulting output are processed properly.
The next step is to import all the necessary namespaces. In addition to including the System.Data and System.Data.SQL namespaces, you are also required to include the System.Xml namespace, because it contains all classes required to process an XML document.
After importing the namespaces, you need to establish a connection with the SQL server and fetch the required data. This is done using the following code:
Dim SQLcon as New SqlClient.SqlConnection (
"server=localhost;uid=sa;pwd=;
database= sales")
Dim SQLcommand as New SqlClient.SqlDataAdapter
("SELECT * FROM
Orders", SQLCon)
Dim dsOrders As New DataSet()
SQLcommand.Fill(dsOrders, "Order")
After you have fetched the data into the data set, you can convert it into an XML document by using the following statement:
Dim XmlDoc as XmlDocument = New XmlDataDocument
(dsOrders)
In this statement, the constructor of the XmlDataDocument class is invoked. The constructor takes the DataSet object as a parameter and loads the data set into the XmlDataDocument object. The reference to this new instance is stored in an object of the XmlDocument class.
Finally, you display the resulting XML document in the Web form. This is done by creating an XML server control with the ID "MyXmlDoc" and setting the Document property of the control to the XmlDocument object created in the previous step:
MyXmlDoc.Document = XmlDoc
You can save the resulting XML document in a file by using the Save() method of XMLDocument. The Save() method takes a string that specifies the name of the file as a parameter. The following statement illustrates this:
Xmldoc.save ("orders.xml")
When you view the ASPX file in a browser, it will display the output as shown in Figure 13-4.