Friday, March 4, 2011

Introduction to XML

Introduction to XML

Introduction
XML stands for Extensible Markup Language. An XML document stores data in the form of text. The data itself can be textual or binary. The binary data is not stored as binary data but is first converted to and is stored as text data. Elements and attributes are used in XML document to encapsulate data in a more logical hierarchical fashion.

This tutorial is 1st one in the series of tutorials about XML and ASP.NET:
  • Introduction to XML

 

Sample XML Document
Following is a simple XML document:
<?xml version="1.0" encoding="utf-8"?>
<article>
 <author isadmin="true">Faisal Khan</author>
 <title>Sample XML Document</title>
 <body>The body of the article goes here.</body>
</article>
XML Declaration
All XML documents start with <?xml version="1.0" ?>. This tells the XML parser that what is to follow is an XML document. An optional encoding attribute is often added as well.
<?xml version="1.0" encoding="utf-8"?>
<article>
 <author isadmin="true">Faisal Khan</author>
 <title>Sample XML Document</title>
 <body>The body of the article goes here.</body>
</article>
Storing Data in an XML Document
The XML document contains text data that is held in its place by a logical hierarchy of elements. The data in the sample XML document, above, is highlighted below:
<?xml version="1.0" encoding="utf-8"?>
<article>
 <author isadmin="true">Faisal Khan</author>
 <title>Sample XML Document</title>
 <body>The body of the article goes here.</body>
</article>
Elements
All XML documents must have a root element. In our sample XML document, the root element is article. All elements must have a starting tag and an ending tag. The name of the element can be anything you want. But it is recommended to keep the element names short and simple to understand e.g., article, full_name, first_name, etc. If an element name has to consist of two words, it is recommended to insert an '_' (underscore) character in the place of space e.g., first_name for "first name". An element is contained between < and > characters. The ending tag has an additional slash '/' just before the name of the element

The elements in the sample XML document are highlighted below:
<?xml version="1.0" encoding="utf-8"?>
<article>
 <author isadmin="true">Faisal Khan</author>
 <title>Sample XML Document</title>
 <body>The body of the article goes here.</body>
</article>
Attributes
An attribute is name/value pair within an element that can store further information for an element. It has to be in the format of name="value". In our XML document, isadmin is the name of the attribute within author element, whose value is "true". The attribute in our XML document is highlighted below:
<?xml version="1.0" encoding="utf-8"?>
<article>
 <author isadmin="true">Faisal Khan</author>
 <title>Sample XML Document</title>
 <body>The body of the article goes here.</body>
</article>
Entity References
Certain characters are illegal to be present in data segments of the elements i.e., between element start and end tags. These characters are &, <, >, ', and ". The reason is that they have special meaning in an XML document. As you read above, XML elements and attributes use these characters to encapsulate data. Now what should you do if you want to use these characters as data in an XML document? Well, make use of entity references.
An "entity" is a name/value pair defined in a DTD (Document Type Definition) file. We will learn more about DTD files later. For now, you should know that an entity can be a name/value pair, just like an attribute, which you can define yourself. While attributes are defined in XML documents, entities (1 ore more) are defined inside DTD files. You can define an entity in an XML document using DTD syntax and make use of it later in the data in your XML document using an entity reference who syntax is: &entityName;. This is dynamic substitution. The XML parser will replace the entity reference at runtime with the value of that entity.
<!ENTITY websiteName "Stardeveloper.com">
Above code defines an entity "websiteName" with the value, "Stardeveloper.com". You can access the value of this entity using an entity reference within your XML document using the syntax &websiteName; as shown below:
<?xml version="1.0" encoding="utf-8"?>
<article>
 <author isadmin="true">Faisal Khan</author>
 <title>Sample XML Document</title>
 <body>This article will be posted at &websiteName;.</body>
</article>

Now that you know what entities are and how entity references can be used to access their values inside the data portions of an XML document, dynamically; you should know that all XML documents can use 5 pre-loaded entity references as given below:
Character Entity Reference
& &amp;
< &lt;
> &gt;
' &apos;
" &quot;
Now, if you want to use any of the 5 special characters as data in your XML document, you can use them using entity references like this:
<?xml version="1.0" encoding="utf-8"?>
<article>
 <author isadmin="true">Faisal Khan</author>
 <title>Sample XML Document</title>
 <body>Now you can use &amp;, &lt;, &gt;, &apos;, and &quot;
 tags as often as you want.</body>
</article>
Summary
Some of the things that we learned about XML documents in this tutorial:
  • How to declare an XML document?
  • How to store data in an XML document?
  • What are elements and how to use elements to provide logical hierarchical access to the data stored in XML document?
  • What are attributes?
  • What are entities and entity references?
The next tutorial, Reading XML File with ASP.NET, illustrates how to read the contents of this XML file in an ASP.NET page.


Reading XML Files with ASP.NET

Introduction
In this tutorial, we will learn how to read the contents of an XML file with ASP.NET. We will make use of the sample XML file which we created in the previous tutorial (Introduction to XML). We will create an ASP.NET page which reads the contents of this XML file and then displays it to the user.

This tutorial is 2nd one in the series of tutorials about XML and ASP.NET:
Sample XML File
Okay, let us get started now. Copy and paste the contents below in a new text file and then save that file as "sample.xml" in the /App_Data sub-folder of your ASP.NET web application. Placing the XML file in /App_Data sub-folder ensures that no one will be able to directly access this file from the web. It will only be accessed by our ASP.NET page which will read and display its contents.
<?xml version="1.0" encoding="utf-8"?>
<article>
 <author isadmin="true">Faisal Khan</author>
 <title>Sample XML Document</title>
 <body>The body of the article goes here.</body>
</article>
Reading the Contents of XML File using XmlDocument class
System.Xml namespace has a class with the name of XmlDocument which we will use to read XML file's contents and display it to the user. Reading the contents of sample.xml file is as easy as these two lines:
XmlDocument doc = new XmlDocument();
 doc.Load(Server.MapPath("~/App_Data/sample.xml"));
Before we delve ourselves deeper into the code, we should create the ASP.NET page first and study its code later.
Reader.aspx
Copy and paste following code into an ASP.NET page and then save it as "reader.aspx":
<%@ Page Language="C#" AutoEventWireup="true" %>

<%@ Import Namespace="System.Xml" %>

<script runat="server">
protected void Page_Load(object source, EventArgs e)
{
 XmlDocument doc = new XmlDocument();
 doc.Load(Server.MapPath("~/App_Data/sample.xml"));

 XmlNode root = doc.DocumentElement;
 AuthorLiteral.Text = root.SelectSingleNode("author").ChildNodes[0].Value;
 TitleLiteral.Text = root.SelectSingleNode("title").ChildNodes[0].Value;
 BodyLiteral.Text = root.SelectSingleNode("body").ChildNodes[0].Value;
}
</script>

<!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 runat="server">
    <title>Reading an XML File</title>
    <style type="text/css">
  body { font-family: Verdana; font-size: 9pt; }
  .name { background-color: #F7F7F7; }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
  <table width="50%" cellpadding="5" cellspacing="2">
  <tr>
   <td class="name">Name</td>
   <td><asp:Literal ID="AuthorLiteral" runat="server" /> 
   <asp:Literal ID="AdminLiteral" runat="server" /></td>
  </tr>
  <tr>
   <td class="name">Title</td>
   <td><asp:Literal ID="TitleLiteral" runat="server" /></td>
  </tr>
  <tr>
   <td class="name">Body</td>
   <td><asp:Literal ID="BodyLiteral" runat="server" /></td>
  </tr>
  </table>
  
    </div>
    </form>
</body>
</html>
When you have properly placed sample.xml file in /App_Data sub-folder and reader.aspx in your web application; you should run the ASP.NET page by accessing it in your browser. On my computer, the ASP.NET page, when run, looked like this:
ASP.NET page displaying the contents of an XML File
ASP.NET page displaying the contents of an XML File
Now that we have created the ASP.NET which successfully reads and displays the contents of our XML file, we should look at the code which is doing the job.
Code to read XML File
We first need to create an instance of XmlDocument class. This class provides methods and properties to access the contents of XML file. This class implements W3C Document Object (DOM) level 1 core and level 2. The DOM is an in-memory tree representation of the XML document, providing easy navigation and editing capabilities.
XmlDocument doc = new XmlDocument();
Next, we need to tell XmlDocument class instance to load our XML file in memory. We do that by calling Load() method of XmlDocument class. Its argument is the complete physical path to the sample.xml file. We use Server.MapPath() method to convert the relative path to sample.xml, to complete physical path.
doc.Load(Server.MapPath("~/App_Data/sample.xml"));
Now that we have sample.xml file in memory, we will use properties and methods of XmlDocument class to read the "name", "title", and "body" elements. To do that first we need to get access to the root element ("article") of the XML file.
XmlNode root = doc.DocumentElement;
Once we have access to the root element, accessing the values contained in "name", "title", and "body" sub-elements is as simple as calling SelectSingleNode() method, and then accessing its ChildNodes collection. The argument to SelectSingleNode() is the name of the element/tag you want to access the value of.
AuthorLiteral.Text = root.SelectSingleNode("author").ChildNodes[0].Value;
TitleLiteral.Text = root.SelectSingleNode("title").ChildNodes[0].Value;
BodyLiteral.Text = root.SelectSingleNode("body").ChildNodes[0].Value;
And that is it. XmlDocument provides even more easy navigability to the contents of its XML file using XPath queries, something which we will explore in future tutorials.
Summary
In this tutorial we learned the code to read XML file in to memory and then access its elements using methods and properties of XmlDocument class. In next tutorial, we will learn how to selectively access the elements of in memory XML file, using XPath queries.

 

Introduction to XPath for ASP.NET Developers

Introduction
XPath is a language for selecting nodes (parts or segments) within an XML document. As you are already familiar with XML, XML is a markup language which uses elements and attributes to encapsulate data in a logical manner. XPath furthers builds on it and provides navigational abilities in an XML document. For example, you can use an XPath query to select one or more nodes within an XML document that match a certain criteria. That criteria can by anything from an element matching a given name to an element whose attribute matches a specific value.

This tutorial is 3rd one in the series of tutorials about XML and ASP.NET:
Tree like representation of an XML Document
In XPath, an XML document is represented as a tree of nodes. There is a parent node with one or more child nodes. While a node in XPath can be of 7 types; for practical purposes, a node in XPath corresponds to an element or attribute within an XML document. For example, have a look at following XML document:
<?xml version="1.0" encoding="utf-8" ?>
<userinfo>
 <username admin="true">someUserName1</username>
 <email>xyz@whatever.com</email>
</userinfo>
Following is XPath's tree representation of the above document:
  • userinfo
    • username
      • admin
    • email
Each node is related to the nodes above and below it. In our XML document above, userinfo is root node. userinfo is the parent of username and email nodes. username and email nodes are siblings. username and email are children of userinfo node. Similarly, admin is the child of username node.
Selecting Nodes within an XML Document
Now that we understand how elements and attributes are represented as nodes in XPath, we will focus on how to use XPath expressions to select one or more nodes within an XML document.

XPath Expressions
Following are some of the expressions that you can use to select one or more nodes from the XML document above:
  • /userinfo - Selects the root element.
  • /userinfo/username - Selects the username node which is the child of userinfo root node.
  • //email - Selects all the nodes in the document which match the name (email) irrespective of where they lie in the document.
  • //username[@admin] - Selects all nodes with the name of "username" which have an attribute; "admin".
  • /userinfo/username[1] - Selects the first username node that is the child of userinfo node.
  • /userinfo/username[last()] - Assuming userinfo had more than one username child nodes, it will return the last username node that is the child of userinfo node.
Practical Demonstration of XPath Expressions
We will now create a sample XML document and then use XPath expressions to select and display only few nodes from it.
Sample XML Document
Copy and paste following text in a new text file and save it as "sample.xml" in the /App_Data folder of your ASP.NET web application:
<?xml version="1.0" encoding="utf-8" ?>
<article>
 <author isadmin="true">Faisal Khan</author>
 <title>Sample XML Document</title>
 <body>
  <page>This is page #1.</page>
  <page>This is page #2.</page>
  <page>This is page #3.</page>
 </body>
</article>
XPath.aspx ASP.NET Page
Now, we will create the ASP.NET page which will read the above sample.xml file and selectively display its contents using XPath. Copy and paste the following text into a new text file and save it as "XPath.aspx" in your ASP.NET web application:
<%@ Page Language="C#" AutoEventWireup="true" %>

<%@ Import Namespace="System.Xml" %>

<script runat="server">
 protected void Page_Load(object source, EventArgs e)
 {
  XmlDocument doc = new XmlDocument();
  doc.Load(Server.MapPath("~/App_Data/sample.xml"));

  XmlNodeList nodes = doc.SelectNodes("/article/body/page");

  foreach (XmlNode node in nodes)
  {
   TableRow row = new TableRow();
   TableCell cell = new TableCell();
   cell.Text = node.FirstChild.InnerText;

   row.Cells.Add(cell);
   PagesTable.Rows.Add(row);
  }
 }
</script>

<!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 runat="server">
    <title>Using XPath Expressions</title>
    <style type="text/css">
  body { font-family: Verdana; font-size: 9pt; }
  .name { background-color: #F7F7F7; }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
  <asp:Table id="PagesTable" runat="server" />
    </div>
    </form>
</body>
</html>
We will look into its code a little later, for now when this ASP.NET page was run on my computer, it produced following result (displaying only page elements from the XML file):


Looking into the Code
We learned how to read an XML file and display its contents using XmlDocument class from System.Xml namespace in an ASP.NET page, in previous tutorial. We will focus in this tutorial on how to use XPath expressions to only selectively return the list of nodes we want to display to the user.
protected void Page_Load(object source, EventArgs e)
{
 XmlDocument doc = new XmlDocument();
 doc.Load(Server.MapPath("~/App_Data/sample.xml"));

 XmlNodeList nodes = doc.SelectNodes("/article/body/page");

 foreach (XmlNode node in nodes)
 {
  TableRow row = new TableRow();
  TableCell cell = new TableCell();
  cell.Text = node.FirstChild.InnerText;

  row.Cells.Add(cell);
  PagesTable.Rows.Add(row);
 }
}
We create a new instance of XmlDocument class and make it load our "sample.xml" file. Next, we want to only display the page elements so we use a simple XPath expression; "/article/body/page" to select only the page nodes.
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/App_Data/sample.xml"));

XmlNodeList nodes = doc.SelectNodes("/article/body/page");
Next, we iterate through the returned list of XmlNodes and insert its contents in our ASP.NET table. To get the text from the page element in XML file, we use XmlNode.FirstChild.InnerText property.
foreach (XmlNode node in nodes)
{
 TableRow row = new TableRow();
 TableCell cell = new TableCell();
 cell.Text = node.FirstChild.InnerText;

 row.Cells.Add(cell);
 PagesTable.Rows.Add(row);
}
Some More XPath Expressions
Had we only wanted to fetch the first page element from the XML document, what is the XPath expression we should have used? And what if we wanted to return only the last page element?
  • Returning the first page only: /article/body/page[1]
  • Returning the last page only: /article/body/page[last()]
Summary
In this tutorial, we learned how to use XPath expressions to select parts and segments from an XML file. In the next tutorial, we will learn how to generate an XML document programmatically using ASP.NET.

 

Introduction to DTD (Document Type Definition)

Introduction
In this tutorial, we will learn about "Document Type Definition". DTD is an XML schema language that is used to describe the structure of an XML document. It describes what elements an XML document can contain and in which order. It further specifies how these elements are arranged within one another and what attributes these elements can contain. The description of the structure and these constraints are written in a formal syntax, some of which we will learn in this tutorial. These declarations can be placed within an XML file, or more commonly in a separate file with ".dtd" extension.

Following topics will be covered in this tutorial:
This tutorial is 5th one in the series of tutorials about XML and ASP.NET:
We will now learn how elements and attributes are declared in DTD, and how DTD declarations can be associated with XML document(s).
Declaring Elements in DTD
An element declaration is used in DTD to describe what content, child element(s), and attribute(s), that element can contain. One element declaration is used for each element within an XML document, separately. We begin with the declaration of the root element in our XML file.
<!ELEMENT article (title, author, body)>
Above DTD element declaration states that there must be a root element with the name of "article" and that element must have child elements with the names of "title", "author" and "body", in that order.
Each element that has been referenced by name in the above declaration, now must have its own separate declaration.
<!ELEMENT article (title, author, body)>
<!ELEMENT title (#PCDATA)> 
<!ELEMENT author (#PCDATA)> 
<!ELEMENT body (#PCDATA)>
Above element declarations that follow the root element declaration ("article") state that these elements can contain character data.

If you want to have the option where you do not put "author" element within an XML document, all you have to do is to put a '?' (question mark) in front of the "author" reference like this:
<!ELEMENT article (title, author?, body)>
<!ELEMENT title (#PCDATA)> 
<!ELEMENT author (#PCDATA)> 
<!ELEMENT body (#PCDATA)>
A '?' (question mark) in front of an element reference means that, that element can be present zero or one time. Now, an XML document without any "author" element (but with article, title and body elements in proper order) can still be a validated successfully against this DTD.
We will learn about the full list of specifiers that can be used in element declarations in future tutorials.
Declaraing Attributes in DTD
An attribute declaration is used in DTD to describe what attribute(s) a given element can have, what content those attributes should have, and whether these attribute(s) are required, implied (not required), or fixed. To explain the syntax of attribute declaration, we will add an attribute with the name of "email" to our "author" element, that we declared above. Here is how we do it:
<!ATTLIST author email CDATA #REQUIRED>
Above attribute declaration states that the "author" element should have an attribute with the name of "email" and that attribute's value should be character data (CDATA). If we wanted to give the option to our XML writer that this attribute can be omitted, we should have used #IMPLIED instead of #REQUIRED in the attribute declaration statement.
Our DTD declarations now look like this:
<!ELEMENT article (title, author?, body)>
<!ELEMENT title (#PCDATA)> 
<!ELEMENT author (#PCDATA)> 
<!ELEMENT body (#PCDATA)>

<!ATTLIST author email CDATA #REQUIRED>
Associating DTD with XML Documents
There are two methods of associating DTD declarations with XML document(s). We will look into both of them.

 

i. Placing DTD Declarations in a separate file
We do that by placing following DTD declarations in a separate file with the name of "article.dtd".
<!ELEMENT article (title, author?, body)>
<!ELEMENT title (#PCDATA)> 
<!ELEMENT author (#PCDATA)> 
<!ELEMENT body (#PCDATA)>

<!ATTLIST author email CDATA #REQUIRED>
By placing DTD declarations in a separate file, we can associate as many XML documents as we want with these DTD declarations, by just adding one line of code in those XML documents.
Here is a sample XML document that conforms to the DTD declarations in article.dtd:
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE article SYSTEM "article.dtd">

<article>
 <title>Sample XML Document.</title>
 <author email="hidden@xyz.com">Faisal Khan</author>
 <body>This is a sample XML Document.</body>
</article>
The DOCTYPE statement highlighted above, is all that is necessary to associate the DTD document with the XML document. Following the DOCTYPE should be the name of root element of the XML document. After that comes the SYSTEM identifier. The last word in this statement is the name of the DTD document containing DTD declarations.
ii. Placing DTD Declarations within an XML Document
We can also place DTD declarations directly in an XML document. This is how it is done:
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE article [
 <!ELEMENT article (title, author?, body)>
 <!ELEMENT title (#PCDATA)> 
 <!ELEMENT author (#PCDATA)> 
 <!ELEMENT body (#PCDATA)>

 <!ATTLIST author email CDATA #REQUIRED>
]>

<article>
 <title>Sample XML Document.</title>
 <author email="hidden@xyz.com">Faisal Khan</author>
 <body>This is a sample XML Document.</body>
</article>
Either of these two methods can be used to associate DTD declarations with XML document(s).
Summary
In this tutorial, we learnt about Document Type Declarations. We learnt that DTD is an ideal way to describe and put constraints on the structure of an XML document. Next, we learnt how to declare elements and attributes. We also learnt how to associate DTD declarations with an XML document.
In the next tutorial, we will learn how to validate an XML document programmatically using an ASP.NET page with DTD declarations in a .dtd file.

Validating an XML Document using DTD in ASP.NET

Introduction
In this tutorial, we will learn how to validate an XML document using DTD. We will develop an ASP.NET page to demonstrate the code. After you are finished reading this tutorial, you will be proficient in writing C# code that validates XML documents using DTD.

Following topics will be covered in this tutorial:
This tutorial is 6th one in the series of tutorials about XML and ASP.NET:
Well-formedness vs Validation
Well-formedness means that an XML document obeys the rules that are necessary for an XML document to be, frankly, an XML document. What this means is that there should be an XML declaration, there should be a root element, the name of element in opening tag must match with the name in the closing tag, and so on. We covered a good part of it in the first article on introduction to XML.
Validation on the other hand is an entirely different thing. An XML document is valid only if it conforms to the constraints declared in DTD. Put it simply, if the structure of an XML document is exactly as it is described in DTD, then that XML document is valid (in reference to that DTD), otherwise it is not.
Validating XML Document using DTD
We will use the sample XML document and DTD file from the article on Document Type Definition. We will then write code to validate that XML document using that DTD.
Sample XML Document
Following is the XML document that we will be using for demonstration:
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE article SYSTEM "article.dtd">

<article>
 <title>Sample XML Document.</title>
 <author email="hidden@xyz.com">Faisal Khan</author>
 <body>This is a sample XML Document.</body>
</article>
Copy above code in a new text file and save it as "article.xml" in the /App_Data folder of your ASP.NET application.
Sample DTD File
Following is the DTD file that we will be using for demonstration:
<!ELEMENT article (title, author?, body)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)> 
<!ELEMENT body (#PCDATA)>

<!ATTLIST author email CDATA #REQUIRED>
Copy above code in a new text file and save it as "article.dtd" in the /App_Data folder of your ASP.NET application.
If you look at the XML document and DTD file closely, you'll see that the XML document conforms to the constraints in the DTD file, and is thus, a valid XML document with respect to that DTD file. To do this manual verfication programmatically, we'll have to write code. Luckily, in .NET, writing code that validates an XML document is quite simple.
ASP.NET Page that Validates an XML Document using DTD
Copy following code in a new text file and save it as "ValidateXml.aspx" in your ASP.NET application:
<%@ Page Language="C#" %>

<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Xml.Schema" %>

<script runat="server">
 private bool valid = true;
 private StringBuilder msgs = new StringBuilder();

 protected void Page_Load(object source, EventArgs e)
 {
  string fullPathToXmlFile = Server.MapPath("~/App_Data/article.xml");

  XmlReaderSettings settings = new XmlReaderSettings();
  settings.ProhibitDtd = false;
  settings.ValidationType = ValidationType.DTD;
  settings.ValidationEventHandler +=
   new ValidationEventHandler(ValidationHandler);

  XmlReader reader = XmlReader.Create(fullPathToXmlFile, settings);

  while (reader.Read())
   ;

  reader.Close();
  reader = null;

  if (valid == true)
   StatusLiteral.Text = "Is Valid";
  else
   StatusLiteral.Text = "Is NOT Valid";

  MessagesLiteral.Text = msgs.ToString();
 }

 protected void ValidationHandler(object sender, ValidationEventArgs args)
 {
  valid = false;

  msgs.Append(args.Message);
  msgs.Append("<br />");
 }
</script>

<!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 runat="server">
    <title></title>
    <style type="text/css">
    body { font-family: Verdana; font-size: 9pt; }
    pre { font-family: Lucida Console; font-size: 8pt; }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div><asp:Label ID="StatusLiteral" runat="server" /></div>
    <pre><asp:Literal ID="MessagesLiteral" runat="server" /></pre>
    </form>
</body>
</html>
Explanation
Since our code is going to be in the language, C#, we declare it as the first line in our ASP.NET page.
<%@ Page Language="C#" %>
Next, we import the namespaces that we will be using in validating the XML document.
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Xml.Schema" %>
We place our code in script tags.
<script runat="server">
 ...
</script>
Before we look at the code, we should see what server side controls we have laid in-between the HTML to display status messages to the user. StatusLiteral will display the success or failure of the validation process in one sentence. MessagesLiteral will display all the failure messages, if any, to the user in detail.
<asp:Label ID="StatusLiteral" runat="server" />
<asp:Literal ID="MessagesLiteral" runat="server" />
Now, we will delve ourselves into the real code that does the validation. We are using two instance level variables to hold the data for this request. The first variable, valid, will be set to false by a segment of code later if the XML document turns out to be invalid. The second variable, msgs, will be appended error messages one after the other (again, if any), and displayed to the user in the end.
private bool valid = true; private StringBuilder msgs = new StringBuilder(); We have placed our code in the Load event of the Page object. This way, every time the page loads, our code will be run.
protected void Page_Load(object source, EventArgs e) { .. } The first thing we do is to get the full physical path to the 'article.xml' file, using Server.MapPath() method.
string fullPathToXmlFile = Server.MapPath("~/App_Data/article.xml");
Note: There is no direct reference to the 'article.dtd' file in the code. It will be loaded by the objects we create later, automatically from the DOCTYPE declaration given in the 'article.xml' file.
Next, we create an instance of XmlReaderSettings object. This object contains the settings we want to use later when are about to the read the XML document. This object is required to create the XmlReader object later. In the settings, we set its properties so that it knows we want to use DTD to validate an XML document. We also set a ValidationEventHanlder method. We do this so that every time an error is thrown if the XML document contains invalid segments, we can set the valid property to false and append the error message to the msgs variable.
XmlReaderSettings settings = new XmlReaderSettings(); settings.ProhibitDtd = false; settings.ValidationType = ValidationType.DTD; settings.ValidationEventHandler += new ValidationEventHandler(ValidationHandler); The working of this event handler has already been explained.
protected void ValidationHandler(object sender, ValidationEventArgs args) { valid = false; msgs.Append(args.Message); msgs.Append("<br />"); } It is this XmlReader object which we create that does the actual job of validating the XML document against that DTD. We create it by calling a static method of XmlReader object and passing as its arguments, the reference to full physical path of the XML document and a reference to the XmlReaderSettings object which we created earlier.
XmlReader reader = XmlReader.Create(fullPathToXmlFile, settings); Once we have created the XmlReader object, we enter a while loop to repeatidly call its Read() method. In each iteration, the XmlReader object examines each node of the XML document. Any error messages that generated during the call to this method are handled by our event handler method we set earlier and are saved to be displayed to the user, later.
while (reader.Read()) ; Once all the nodes have been examined, we close the XmlReader object.
reader.Close(); reader = null; We set the text to be displayed to the user depending if the valid variable is true or false. This variable will be false if even a single error was encountered during validating the XML document.
if (valid == true) StatusLiteral.Text = "Is Valid"; else StatusLiteral.Text = "Is NOT Valid"; Error messages, if any, are set to the appropriate control, to be displayed to the user.
MessagesLiteral.Text = msgs.ToString();
 



 

 

Creating new XML Document in ASP.NET Programmatically

Introduction
In this tutorial, we will learn how to create an XML Document programmatically. We will make use of XmlDocument class from System.Xml namespace. Following topics will be covered in this tutorial:
  • How to create XML declaration and element nodes.
  • How to create attributes and append them to element nodes.
  • How to create CDATA sections within element nodes.
  • How to nest elements and attributes in one another to create a logical tree like structure.
  • How to send the dynamically generated XML document to the client browser with proper headers.
Creating new XML Document
We will now write down the code to create new XML document.
Code for ASP.NET page
Copy and paste following code into a new text file and then save it as "CreateXmlDocument.aspx" in your ASP.NET web application:
<%@ Page Language="C#" AutoEventWireup="true" ContentType="text/xml" %>

<%@ Import Namespace="System.Xml" %>

<script runat="server">
  protected void Page_Load(object source, EventArgs e)
  {
    XmlDocument doc = new XmlDocument();

    // XML declaration
    XmlNode declaration = doc.CreateNode(XmlNodeType.XmlDeclaration, null, null);
    doc.AppendChild(declaration);

    // Root element: article
    XmlElement root = doc.CreateElement("article");
    doc.AppendChild(root);

    // Sub-element: author
    XmlElement author = doc.CreateElement("author");
    author.InnerText = "Faisal Khan";
    root.AppendChild(author);

    // Attribute: isadmin
    XmlAttribute isadmin = doc.CreateAttribute("isadmin");
    isadmin.Value = "true";
    author.Attributes.Append(isadmin);
    
    // Sub-element: title
    XmlElement title = doc.CreateElement("title");
    title.InnerText = "Sample XML Document";
    root.AppendChild(title);

    // Sub-element: body (CDATA)
    XmlElement body = doc.CreateElement("body");
    XmlNode cdata = doc.CreateCDataSection("This is the body of the article.");
    body.AppendChild(cdata);
    root.AppendChild(body);
    
    doc.Save(Response.OutputStream);
  }
</script>

Click Here
Explanation
The first thing we do in our ASP.NET page is to declare, that we will use "C#" as the programming language and that, the content-type of this ASP.NET page will be "text/xml".
Note: The content-type of an XML document should be "text/xml" for it to be properly handled by the client browser.
<%@ Page Language="C#" AutoEventWireup="true" ContentType="text/xml" %>
Next, we import "System.Xml" namespace in our ASP.NET page. The XmlDocument class we will use later to generate an XML document dynamically, is present in this namespace.
<%@ Import Namespace="System.Xml" %>
A 'script' tag whose 'runat' attribute is set to "server" is required for ASP.NET to process this code on the server-side.
<script runat="server">
 ...
</script>
We are going to handle the Load event of the ASP.NET page and place the code to generate XML document dynamically, in the Page_Load() method.
protected void Page_Load(object source, EventArgs e)
{
 ...
}
First, we create a new instance of XmlDocument class.
XmlDocument doc = new XmlDocument();
Every XML document has a declaration statement as the first line of the document, enclosed in <?xml and ?> tags and having an attribute with the name of 'version', whose value it set to "1.0":
<?xml version="1.0" ?>
To create this declaration, we call the CreateNode() method of XmlDocument class. The first argument to this method is the type of node you want to create. We pass XmlNodeType.XmlDeclaration as the type because we want to create an XML declaration node. Once that node is created, we pass its reference to the AppendChild() method of XmlDocument instance we created earlier to append this node in the XML document we are generating.
Note: If you do not append the newly created declaration node in the XmlDocument instance, it will not appear in the XML document.
// XML declaration
XmlNode declaration = doc.CreateNode(XmlNodeType.XmlDeclaration, null, null);
doc.AppendChild(declaration);
Next, we create the root element of our XML document. A root element is the element in which all other elements are nested i.e., are sub-elements of the root element.
To create the root element, we call the CreateElement() method of XmlDocument class and as its argument, we pass the name of the root element, "article". And like before, we append this element to the XmlDocument instance.
Note: The name of the root element can be anything. For the purpose of this tutorial, we are naming it "article".
// Root element: article
XmlElement root = doc.CreateElement("article");
doc.AppendChild(root);
The XML document at this moment, if generated, will look like this:
<?xml version="1.0"?>
<article />
Next, we create a sub-element and nest it in the root element. To do that, we call the CreateElement() method of XmlDocument instance, and as its argument, we pass the name of this element, "author". Then we set the inner text of that element by setting the InnerText property of newly created XmlElement object. Finally, as before to make this element appear in the XML document, we append this element to the root element.
// Sub-element: author
XmlElement author = doc.CreateElement("author");
author.InnerText = "Faisal Khan";
root.AppendChild(author);
At this moment, if generated, the XML document will look like this:
<?xml version="1.0"?>
<article>
 <author>Faisal Khan</author>
</article>
 
Next, we create an attribute using CreateAttribute() method of XmlDocument class. We pass as its argument, the name of the attribute, "isadmin". We then set the value of this attribute using Value property of the newly created XmlAttribute object. Finally, we append this attribute to the "author" element, we had created earlier.
// Attribute: isadmin XmlAttribute isadmin = doc.CreateAttribute("isadmin"); isadmin.Value = "true"; author.Attributes.Append(isadmin); The XML document, if generated at this moment, will look like this:
<?xml version="1.0"?> <article> <author isadmin="true">Faisal Khan</author> </article> So far so good. We will quickly create one more element and append it to the root element.
// Sub-element: title XmlElement title = doc.CreateElement("title"); title.InnerText = "Sample XML Document"; root.AppendChild(title); The XML document, if generated at this moment, will look like this:
<?xml version="1.0"?> <article> <author isadmin="true">Faisal Khan</author> <title>Sample XML Document</title> </article> We will create one more element with the name of "body", using the same technique we learned above. But this time, the content of this element will be a CDATA section. A CDATA section is a special section within the content of an element in an XML document. As we learned in Introduction to XML tutorial, there are five characters which have special meaning in an XML document. When they are present in the inner text of an element, they are converted to entity references to prevent the XML document from throwing an exception. For example, the character '<' is converted to "&lt;". Within a CDATA section, these characters are not converted to entity references. To prevent the XML reading software from throwing an exception, the content of a CDATA section is enclosed in <![CDATA[ and ]]> character sequences.
To create the CDATA section, we call the CreateCDataSection() method of XmlDocument instance and passing as its argument, the content we want to place in that section. This section is then appended to the newly created element. The newly created element, itself, is then appended to the "body" element.
// Sub-element: body (CDATA) XmlElement body = doc.CreateElement("body"); XmlNode cdata = doc.CreateCDataSection("This is the body of the article."); body.AppendChild(cdata); root.AppendChild(body); We are done creating the XML document. This is what the final document should produce when run:
<?xml version="1.0"?> <article> <author isadmin="true">Faisal Khan</author> <title>Sample XML Document</title> <body><![CDATA[This is the body of the article.]]></body> </article>

To send this document to the client browser, we call the Save() method of XmlDocument class and as its argument, pass the reference to ASP.NET page's HttpResponse.OutputStream object.
doc.Save(Response.OutputStream);
When this ASP.NET page was run on my computer, it looked like this in Internet Explorer:
Programmatically Created XML Document
Programmatically Created XML Document
Summary
In this tutorial, we learned how to create an XML document programmatically using XmlDocument class. In the next tutorial, we will learn about DTD (Document Type Definition), which is a markup language used to describe the structure of an XML document. If an XML document conforms to a given DTD, then that XML document is valid, otherwise it is not.

 

Web Services Tutorial: Understanding XML and XML Schema-Part 1

Abstract

This Web Service article series covers all the important standards in the Web Services stack and ties them together with real-world examples. The first article in this series discusses XML (Extended Markup Language). XML provides a significant advance in how data is described and exchanged by Web-based applications using a simple, flexible, standards-based format. The article focuses on XML Schema, an important component of creating XML documents.

Introduction

By now, you would have heard about Web Services—a technology that can change the future of computing and e-commerce. Web Services is a distributed computing technology that offers interaction and collaboration among vendors and customers, with the vision of providing ubiquitous computing.
When you plug an appliance into the electricity socket, you don't worry about how the electricity generation and distribution takes place. All you care about is uninterrupted power and of course the utility bill that you get at the end of the month! Similarly, Web Services will make computing resources, both hardware and software, accessible to you through the Internet just like electricity is made available to you. Web Services will do for computing what the Internet did for data. They would encourage a pay-per-usage model and make dynamic collaborations possible. One of key definitions of Web Services is: "Web Services are loosely coupled software components delivered over Internet-standard technologies."
Some of the early products in Web Services started appearing in 1997 when Sun announced its Jini platform and Hewlett-Packard its e-speak. After that, many big players such as IBM and Microsoft joined this race. The Web Services arena picked up steam after the big players roped in and several small players also joined hands for what was perceived as the next Internet wave. Server-standard body consortiums were formed, which developed numerous standards on different aspects of Web Services. Some of the key standard bodies consortiums are: W3C, Oasis, JCP, OMG, and several individual efforts by a group of companies.
    Two of the key problems solved by Web Services over earlier distributed systems such as CORBA, DCOM, RPC, and so forth were:
    • Interoperability: Earlier distributed systems suffered from interoperability issues because each vendor implemented its own on-wire format for distributed object messaging. By using XML as an on-wire standard, the two camps of Java/J2EE and .NET/C# now could speak to each other.
    • Firewall traversal: Collaboration across corporations was an issue because distributed systems such as CORBA and DCOM used non-standard ports. As a result, collaboration meant punching a hole in your firewall, which was often unacceptable to IT. Hence, this did not allow any dynamic collaboration, as it required going through a manual process for collaborating with partners. Web Services use HTTP as a transport protocol and most of the firewalls allow access though port 80 (for HTTP), leading to easier and dynamic collaboration. The dynamic nature of Web Services interaction offers several exciting services for the users.
    What are the key technologies that made Web Services possible? Let us now examine the key interactions and the key standards involved in the Web Services stack.

    Web Services Stack

    To understand what technologies are required for Web Services, we need to understand a typical Web Service interaction.
    The Web Services model follows the publish, find, and bind paradigm. In the first step, a service provider publishes a Web Service in a Web Service registry. Secondly, a client who is looking for a service to meet their requirement searches in a registry. After successfully finding multiple matches, it chooses a service. The client then chooses a service based on its preferences. The client then downloads the service description and binds with that to invoke and use the service.

    One of the primary concerns of Web-based programmers was how to transmit data in an interoperable manner. At the bottom-most layer is the XML standard that addresses this. SOAP (Simple Object Access Protocol) is an XML-based mechanism for messaging and RPC (Remote Procedure Calls). It addresses the fundamental problem of firewall traversal in RPC systems by using HTTP as the transport. SOAP is the protocol used for invoking the service.



    Click here for a larger image.

    WSDL (Web Services Description Language) provides an XML-based way of describing a Web Service, giving details of using it. WSDL is an XML equivalent of IDL (Interface Definition Language), used in the RPC days. UDDI (Universal Description Discovery Integration) provides a "Yellow page" directory of Web Services, making it easier for clients to discover the services of their choice. The service provider publishes the service description (WSDL) and other searchable details in the UDDI registry. A client uses UDDI to perform the find of a service.
    In this tutorial series, we will cover each and every standard in the Web Service stack moving from the bottom up, beginning with XML.

    XML

    Extensible Markup Language (XML) is a extensible, portable, and structured text format. XML is playing an increasingly important role in the exchange of a wide variety of data on the Web and elsewhere. XML was derived from SGML, which was a complex language for defining other markup languages.
    XML initiative consists of bunch of related standards. Apart from the core XML standard, it includes XSL—Extensible Stylesheet language, which is used to transform XML data into a customizable presentation. XLink and XQuery provide a way to provide flexible query facilities to extract data from real and virtual XML documents on the Web. XPath and XPointer are languages for addressing parts of an XML document.
    A previous article, "Understanding XML," introduced you to the fundamentals of XML. XML Schema is one of the key components of XML. Therefore, in this article we will closely look at working with XML Schema.

    Working with XML

    When working with XML, we think of creating XML documents and consuming XML documents. The creation process involves using editors and tools to create XML documents. On the other hand, consuming XML documents involves parsing the XML documents and extracting the useful data.

    Creating XML documents

    Creating XML documents is a two step process, which involves:
    • Defining the grammar and restrictions over data for the XML document.
    • Creating the XML document itself. This document can be validated against the grammar.
    The DTD and Schema are used to describe the grammar and restriction over data in the XML document.

    DTD and Schema

    DTD and schema are used to specify the structure of instance documents and the datatype of each element/attribute. DTDs used today in the XML originated from the parent SGML specification. Because SGML was designed for a more document-centric model, it did not require the use of complex datatyping definitions. The XML Schema specification improves greatly upon the DTD content model by providing rich datatyping capabilities for elements and attributes as well as providing OO design principles.
    XML Schema was approved as a W3C Recommendation in May, 2001 and is now being widely used for structuring XML documents for e-commerce and Web Services applications.
    The two major goals that the W3C XML Schema working group focused on during the design of the XML Schema standard were:
    • Expressing Object Oriented design principles found in common OO programming languages into the specification.
    • Providing rich datatyping support similar to the datatyping functionality available in most relational database systems.
    XML Schemas provides a means of creating a set of rules that can be used to identify document rules governing the validity of the XML documents that you create. Schemas provide a means of defining the structure, content, and semantics of XML documents that can be shared between different types of computers and documents.

    Advantages of XML Schema

    XML Schema offers many advantages over DTD:
    • Enhanced data types: Schema supports over 44 datatypes versus 10 supported by DTD. You can create your own data type in XML Schema. For example: "This is a new type based on the string type and elements of this type must follow this pattern: ddd-dddd-ddd, where 'd' represents a digit".
    • Written in the same syntax as instance documents: DTD requires you to remember another syntax than the one used to write XML documents. Remembering an extra set of syntax is an overhead and is error-prone.
    • Object-oriented: Schemas can extend or restrict a type (derive new type definitions on the basis of old ones).
    • Schemas can specify element content as being unique (keys on content) and uniqueness within a region. They can also define multiple elements with the same name but different content—by using namespaces. Lack of namespaces was a major drawback in DTD. You can think of namespaces in XML like namespaces in C++. A simple analogy of DTD vs. Schema namespace usage is the use of global and local variable in programming languages. A local variable's name is unique with in its scope, whereas a global variable has to be unique across functions. Similarly, with a XML Schema namespace you have freedom to define datatypes without worrying about name collisions.

    Well formedness and Validity

    Well formedness of an XML document (also known as instance document) refers to the characteristic of a document adhering to the XML rule of well formedness. As you would recall, XML has a stringent set of rules unlike HTML, such as closing all the tags, no nested tags, and so forth.
    One quick way of checking well formedness of an XML document is opening it in a browser window. Both Inernet Explorer and Netscape provide automatic well formedness checking and show if any errors shown shows up in the browser.
    Validity of an instance document implies that the document conforms to the specified Schema or DTD file mentioned in the XML document.

    Example of XML Schema

      The following diagram shows the vocabulary for defining XML Schema document.

      Each of the key words is easy to understand. An element is represented by "element" tag. A complexType provides us with a mechanism to define complex user types. Let us now look at an example of Schema for BookStore that can contain multiple books.
      <?xml version="1.0"?>
      <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                            targetNamespace="http://www.books.org"
                            xmlns=http://www.books.org>  A
      <xsd:element name="BookStore">  B
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element ref="Book" minOccurs="1" maxOccurs="unbounded"/>
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>
      <xsd:element name="Book">  C
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element ref="Title" minOccurs="1" maxOccurs="1"/>
            <xsd:element ref="Author" minOccurs="1" maxOccurs="1"/>
            <xsd:element ref="Date" minOccurs="1" maxOccurs="1"/>
            <xsd:element ref="ISBN" minOccurs="1" maxOccurs="1"/>
            <xsd:element ref="Publisher" minOccurs="1" maxOccurs="1"/>
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>
      <xsd:element name="Title" type="xsd:string"/>  D
      <xsd:element name="Author" type="xsd:string"/>
      <xsd:element name="Date" type="xsd:string"/>
      <xsd:element name="ISBN" type="xsd:string"/>
      <xsd:element name="Publisher" type="xsd:string"/>
      </xsd:schema>
      For easy referencing of the XML document, I have marked the document in various sections. In section A of the document, the first line contains the value of xsd as a namespace. Any namespace reference is depicted by using this value as a prefix and the syntax to refer to an element in namespace is namespace:elementname (for example, xsd:element). The targetNamespace attribute specifies the namespace in which the newly defined types reside. In the above example, the defined types of BookStore, Book, Title, Author, ISBN, and Publisher reside in the namespace http://www.books.org.

      The namespace http://www.books.org
      The xmlns attribute defines the default namespace; in other words, from the location at which the elements would be looked for in absence of any namespace prefix for an element.
      In the section B a new type, BookStore, is defined as a complexType, which consists of a sequence of the Book type. A complexType is used to define a user type, which can contain multiple elements and attributes. Section C details the Book type, which itself a complexType consisting of sequence of elements Title, Author, Date, ISBN, and Publisher. The attributes minOccur and maxOccur define the constraint on the occurrence of the elements. The order of the elements in the Book type should follow the order in declaration. In other words, the Book type will contain a Title element, followed by Author, and so on.
      Section D defines the types of individual elements for Book. Each of the elements are of built in a simpleType string.
      You can define your own simpleType, but a simpleType does not consist of multiple elements or any attribute. The simpleType is usually defined to represent a restriction on the datatype. For example, here is the definition for a simple type elevation that can have valid values between 50 and 12000.
      <xsd:simpleType name="elevation">
        <xsd:restriction base="xsd:integer">
          <xsd:minInclusive value="50"/>
          <xsd:maxInclusive value="12000"/>
        </xsd:restriction>
      </xsd:simpleType>
      Having looked at the Schema document, let's look at an instance document using the above schema.
      <?xml version="1.0"?>
      <BookStore xmlns ="http://www.books.org"  1
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  2
                 xsi:schemaLocation="http://www.books.org/
                                     BookStore.xsd">  3
          <Book>  4
                  <Title>Web Services Security</Title>
                  <Author>Ravi Trivedi</Author>
                  <Date>Dec, 2002</Date>
                  <ISBN>1861007655</ISBN>
                  <Publisher>Wrox Publishing</Publisher>
              </Book>
      </BookStore>
      The first definition of xmlns uses a default namespace declaration, and tells the schema-validator that all of the elements used in this instance document come from the Book namespace. The second definition tells the schema-validator that the schemaLocation attribute we are using is the one in the XMLSchema-instance namespace. The third definition, with schemaLocation, tells the schema-validator that the http://www.books.org namespace is defined by BookStore.xsd (in other words, schemaLocation contains a pair of values). This file would be looked up by the schem validator to validate the references the current document.
      Lastly, in the fourth declaration, a Book element is declared which contains the details of a book. Note how the order of the elements is retained in the complexType Book.
      One of the major advantages of the XML Schema specification is that it uses XML as its underlying syntax. By using XML, existing XML parsers can be used in conjunction with Schema validators to provide well-formedness and validation facilities.
      The XML Schema specification plays an important role in the design and implementation of Web Services. WSDL files are also built using XML Schema as the underlying syntax.
      The XML Schema offers an automated mechanism for validating the XML documents. It has been observed that in a typical program, up to 60% of the code is spent checking the data. If your data is structured as XML, and there is a schema, you can hand the data-checking task off to a schema validator. Thus, your code is reduced by up to 60%. Also, next time if your constraints change or you add new elements, you need not write new code to check for new values of elements.

      Summary

      In this article, we briefly looked at the Web Services vision and the standards in the Web Services stack. The XML standard forms the underlying layer for the Web Services technology. XML Schema is used to describe the grammar and constraints on the elements of an XML instance document.
      The XML Schema specification allows for the use of both built-in and custom defined datatypes making it possible to more accurately express and constrain data found in compliant XML documents. Reuse thru inheritance and groupings, similar to functionality found in OO programming languages, is also provided. This provides a flexible and useful mechanism for automatic data validation.
      The next article in this series will cover the creation of XML schemas and the parsing of XML documents.

      Use XML to send SMS messages

      Summary:  Many developers tend to think of Web services as a way to easily move information from one place to another, but it's also important to understand how integral a Web service can be to the overall application. This tip gives some examples of using XML for Short Message Service (SMS) messages. If you're familiar with SMS, you'll find out how adding this tool to your toolbox can help you; if you're not an SMS developer, you'll see a real-life example of how Web services are integrated into an application

      Most of the time, when people talk about Web services, they think of two different scenarios: performing a remote procedure call, or moving data from one place to another. In this tip, I show you a situation in which the message is the medium: SOAP messages that carry on an SMS transaction. This situation truly takes advantage of the SOAP message structure. The header can be used for purposes such as billing or authentication, and the body passes the actual messages.
      I start by looking at SMS itself.
      What is SMS?
      Short Message Service (SMS) is the term used for short (typically less than 160 characters) messages that are sent between mobile phones -- instant messaging for the mobile set, if you will. It's hugely popular in parts of Europe and Japan, and is slowly gaining popularity in the United States. Typically, it works like this:
      • You send a Short Message from your phone to your friend's phone. The message goes to a Message Center.
      • If your friend is available -- meaning, her phone is turned on, and she's in the service area -- the Message Center sends it to her phone.
      • If she's not available, the Message Center holds onto the message.
      • When your friend becomes available, her phone requests the messages, which are then delivered.
      In this way, SMS is more like e-mail than paging or cell phones, even though phones are usually where they come into play.
      For some time now, these transactions have been carried out using HTTP, but each vendor has created its own implementation, leading to interoperability problems. To solve this problem, the SMS Forum has developed two specifications:
      • Short Message Application Part (SMAP) is an XML format for the messages themselves.
      • Mobile Message Access Protocol (MMAP) is a SOAP-based protocol for sending those messages.
      In this tip, I look at how SMAP and MMAP work.

      SMAP messages
      The heart of an MMAP transaction is the actual message to be passed, which gets expressed as an SMAP message. The SMAP protocol was developed on the theory that when compared to the binary form that SMS messages currently take, this XML-based format is more interoperable in the short-term and easier to convert to other formats later on, if necessary.
      When it comes to structure, a simple SMAP text message to be passed to a phone has much in common with a SOAP message.

      Listing 1. SMAP text message
      <SMAP:SubmitRequest 
                xmlns:SMAP="http://www.smsforum.net/schemas/smap/v1.0"
                xsi:schemaLocation="http://www.smsforum.net/schemas/smap/v1.0
                          http://www.smsforum.net/schemas/smap/v1.0/smap.xsd">
         <SMAP:ShortMessage>
      
            <SMAP:Header>
               <SMAP:Destination>
                  <SMAP:Number>5555309</SMAP:Number>
               </SMAP:Destination>
            </SMAP:Header>
      
            <SMAP:Body>
               <SMAP:Text>Jenny, I've got your number.</SMAP:Text>
            </SMAP:Body>
      
         </SMAP:ShortMessage>
      
      </SMAP:SubmitRequest>

      The SMAP text message consists of a header, which contains meta information (such as the destination for the message), and the body, which contains the actual message.
      SMAP defines several operations, from sending a message to altering or cancelling a message that has been sent but not delivered.

      A simple MMAP conversation
      The nice thing about MMAP, in my opinion, is that it takes advantage of the SOAP message structure. The header is used for meta-information, such as billing and session coordination, and the body is used for the message itself.
      Consider, for example, the simplest possible situation: An application sends a message to a particular phone. This is considered an immediate mode situation, and might look something like this:

      Listing 2. MMAP transaction
      <?xml version="1.0" encoding="UTF-8"?>
      <SOAP:Envelope
           xmlns:SOAP="http://www.w3.org/2003/05/soap-envelope"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.w3.org/2003/05/soap-envelope
                     http://www.w3.org/2003/05/soap-envelope">
         <SOAP:Header>
      
            <MMAP:MMAPHeader SOAP:mustUnderstand="1"  
               xmlns:MMAP="http://www.smsforum.net/schemas/mmap/v1.0"
               xsi:schemaLocation="http://www.smsforum.net/schemas/mmap/v1.0
                         http://www.smsforum.net/schemas/mmap/v1.0/mmap.xsd">
      
               <MMAP:ApplicationContext bodyType="Request" 
                                   sourceOperationReference="1138"/>
      
            </MMAP:MMAPHeader>
      
         </SOAP:Header>
         <SOAP:Body>
      
            <SMAP:SubmitRequest 
                     xmlns:SMAP="http://www.smsforum.net/schemas/smap/v1.0"
                     xsi:schemaLocation="http://www.smsforum.net/schemas/smap/v1.0
                               http://www.smsforum.net/schemas/smap/v1.0/smap.xsd">
               <SMAP:ShortMessage>
                  <SMAP:Header>
                     <SMAP:Destination>
                        <SMAP:Number>5555309</SMAP:Number>
                     </SMAP:Destination>
                  </SMAP:Header>
                  <SMAP:Body>
                     <SMAP:Text>Jenny, I've got your number.</SMAP:Text>
                  </SMAP:Body>
               </SMAP:ShortMessage>
            </SMAP:SubmitRequest>
      
         </SOAP:Body>
      </SOAP:Envelope>
                  

      The SOAP:Header contains the MMAPHeader, which contains information about the request itself. The ApplicationContext specifies the type of message as a Request, SuccessResponse, or ErrorResponse. It also provides a sourceOperationReference, an identifier that gets included in the response, so the requester can recognize it. Because of the SOAP:mustUnderstand attribute, if the receiver doesn't understand the MMAPHeader, it must reject the message to avoid processing it incorrectly.
      The SOAP:Body contains the actual SMAP message.

      Listing 3. SMAP message
      <SOAP:Envelope xmlns:SOAP="http://www.w3.org/2003/05/soap-envelope"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.w3.org/2003/05/soap-envelope
                                        http://www.w3.org/2003/05/soap-envelope">
         <SOAP:Header>
      
            <MMAP:MMAPHeader SOAP:mustUnderstand="1"  
                xmlns:MMAP="http://www.smsforum.net/schemas/mmap/v1.0"
                xsi:schemaLocation="http://www.smsforum.net/schemas/mmap/v1.0
                     http://www.smsforum.net/schemas/mmap/v1.0/mmap.xsd">
      
               <MMAP:ApplicationContext bodyType="Request" 
                          sourceOperationReference="1138"/>
               <MMAP:ServiceContext serviceName="wallart">
                <MMAP:AccessControl>
                  <MMAP:ApplicationIdentity>BRoom</MMAP:ApplicationIdentity>
                  <MMAP:Authentication>
                      <MMAP:Password>titogi</MMAP:Password>
                  </MMAP:Authentication>
                </MMAP:AccessControl>
               </MMAP:ServiceContext>
      
            </MMAP:MMAPHeader>
      
         </SOAP:Header>
         <SOAP:Body>
      ...

      At present, you can use plain text or MD5-encoded passwords, but the SMS Forum plans to extend this capability to include stronger security, such as certificates and tokens.
      You can also use the ServiceContext to specify billing information. For example:

      Listing 4. Using the ServiceContext to specify billing information
      ...
               <MMAP:ServiceContext serviceName="wallart">
                  <MMAP:AccessControl>
                     <MMAP:ApplicationIdentity>BRoom</MMAP:ApplicationIdentity>
                     <MMAP:Authentication>
                         <MMAP:Password>titogi</MMAP:Password>
                     </MMAP:Authentication>
      
                     <MMAP:Billing identity="229ss">
                      <MMAP:Cost type="debit">
                        <MMAP:CostAmount amount=".3" units="dollar"/>
                      </MMAP:Cost>
                      <MMAP:ApplyTo>
                        <MMAP:Name>Tommy Heath</MMAP:Name>
                        <MMAP:Account>92988322</MMAP:Account>
                      </MMAP:ApplyTo>
                      <MMAP:Description>Per Message Plan</MMAP:Description>
                     </MMAP:Billing>
      
                  </MMAP:AccessControl>
               </MMAP:ServiceContext>
      ...

      The specification also allows you to add arbitrary HTML code to the Billing element, as long as it's well-formed.

      Message responses
      Once the message is received and dealt with, the receiver sends a response. If all has gone well, it sends a SuccessResponse, such as:

      Listing 5. Sample SuccessResponse
      <SOAP:Envelope xmlns:SOAP="http://www.w3.org/2003/05/soap-envelope"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://www.w3.org/2003/05/soap-envelope
                                       http://www.w3.org/2003/05/soap-envelope">
         <SOAP:Header>
            <MMAP:MMAPHeader SOAP:mustUnderstand="1"
                   xmlns:MMAP="http://www.smsforum.net/schemas/mmap/v1.0"
                   xsi:schemaLocation="http://www.smsforum.net/schemas/mmap/v1.0
                             http://www.smsforum.net/schemas/mmap/v1.0/mmap.xsd">
               <MMAP:ApplicationContext bodyType="SuccessResponse"
                                       sourceOperationReference="1138"/>
            </MMAP:MMAPHeader>
         </SOAP:Header>
         <SOAP:Body>
      
            <SMAP:SubmitResponse 
                xmlns:SMAP="http://www.smsforum.net/schemas/smap/v1.0"
                xsi:schemaLocation="http://www.smsforum.net/schemas/smap/v1.0
                     http://www.smsforum.net/schemas/smap/v1.0/smap.xsd">
      
               <SMAP:MessageRef>3263827</SMAP:MessageRef>
      
            </SMAP:SubmitResponse>
      
         </SOAP:Body>
      </SOAP:Envelope>

      In this case, the body contains a SubmitResponse with a reference number, but no indication of whether the operation succeeded or not. That information resides in the ApplicationContext element, where the bodyType is set as SuccessResponse. The sourceOperationReference refers back to the value provided with the original request, so they can be correlated.

      Other options
      I haven't even begun to scratch the surface of all that you can do using MMAP and SMAP to send SMS messages with XML. The MMAP protocol supports not only this type of simple immediate message, but also sessions -- and even peer-to-peer connections -- in which both parties exchange information asynchronously within a single session. Between all of the capabilities that are built into MMAP, and the fact that it is designed to prevent interoperability problems, you'll find that it allows you to build sophisticated applications based on SMS.


      Thursday, March 3, 2011

      XML In .NET

      One of the most exciting recent advances in computing has been XML. Designed as a stricter and simpler document format than SGML, XML is now used everywhere to produce cross-platform interoperable file formats.
      It's also core to .NET, and is something every .NET developer will need to come to grips with. I've tried to keep this introduction to XML as broad as possible, so it should be of use to users of all developmental persuasions.
      XML 101: Learning to Crawl
      Before we look into the specifics of XML, it is important to know why XML exists and where it can be used. A proper understanding will allow you to use it effectively in your projects.
      Where HTML was designed to display data and specify how that data should look, XML was designed to describe and structure data. In this way, an XML file itself doesn't actually do anything. It doesn't say how to display the data or what to do with data, just as a text file doesn't.
      But XML crucially differs from plain text in that it allows you to structure your data in a standard manner. This is important -- it means that other systems can interpret your XML, which is not as easily achievable in plain text. This describes what is meant by "interoperable file format" -- once you produce an XML file, it is open to everyone. An input, and all the information required to understand the structure of your data, is included in the file.
      Let's take an example. Here's a text file and an XML file that both store the same information:
      mymusic.txt
      The Bends,Radiohead, Street Spirit
      Is This It?,The Strokes, Last Nite

      mymusic.xml
      <catalog>
      <cd>
         <title>The Bends</title>
         <artist>Radiohead</artist>
         <tracks>
           <track name="Street Spirit"/>
         </tracks>
       </cd>
      <cd>
         <title>Is This It?</title>
         <artist>The Strokes</artist>
         <tracks>
           <track name="Last Nite"/>
         </tracks>
       </cd>
      </catalog>

      Notice how the subject of our data is defined in the XML file. We can see clearly that there is a catalogue containing CDs, each of which contains some tracks (music aficionados will notice that I have cut down the track listings for space!). You can also see that XML can be less efficient than some other file formats. Yet, in many cases, the loss in efficiency that results from the increased size can be made up by the speed of processing a well-defined XML file, as parsers (programs that read XML) can predict the structure.
      The way we'd interpret the plain text file would be dependent on how we designed our own format. No information exists to tell others what the actual data means, its order, or how to parse (read) it in other projects. By contrast, the XML file shows clearly what each piece of information represents and where it belongs in the data hierarchy. This "data-describing data" is known as metadata, and is a great strength of XML in that you can create your own specifications and structure your data to be interpreted by any other system.
      Terminology
      To start using XML effectively, a sound knowledge of its terminology and file structures needs to be gained.
      <catalog>
      <cd>
         <title>The Bends</title>
         <artist>Radiohead</artist>
         <tracks>
           <track name="Street Spirit"/>
         </tracks>
       </cd>
      </catalog>

      XML files are hierarchical, with each tag defining an element. All elements need both an opening and a closing tag (<catalog> being an opening tag, </catalog> being its closing tag). Some elements are self-contained and do not require any information to be enclosed. These tags can be made self-closing by the addition of "/>" to the end of the opening tag, as with the track element above.
      The structure of the catalogue is such that it contains CDs, which in turn contain tracks. This is our hierarchy, and will be important later, when we need to parse the document. For example, the track "Street Spirit" corresponds to the CD "The Bends," just as the track "Last Nite" corresponds to the CD "Is This It?" If we didn't use a suitable hierarchy, we wouldn't be able to ascertain this during parsing.
      Sometimes, it doesn't make sense for information to appear between opening and closing tags. For example, if we need more than one piece of information to describe an element, we might like to include those multiple pieces of information within a single tag. We therefore define attributes of the element in the form attribute="value".
      Once you have produced your own set of elements and structures, these formats can be referred to as dialects. For example, RSS is an XML dialect.
      Namespaces
      With so many different dialects floating around, conflicts of meaning can easily arise. For example, take the following XML files, both of which describe some data:
      <film-types>
       <film-type>Action</film-type>
       <film-type>Adventure</film-type>
      </film-types>

      <film-types>
       <film-type>black and white</film-type>
       <film-type>colour</film-type>
      </film-types>

      The first file specifies genres of movies, while the second specifies different types of camera film. But, as the consumers of these files, how can we differentiate between them?
      Namespaces provide the answer. An XML namespace allows us to qualify an element in the same way as telephone area codes qualify phone numbers. There might be thousands of telephone numbers of 545-321. When we add an area code and, perhaps, an international code, we make the number unique: +44 020 545-321.
      The "area code" for XML namespaces is a URI, which is associated with a prefix for the namespace. We define a namespace using an xmlns declaration, followed by the prefix, which is equal to a URI that uniquely identifies the namespace:
      xmlns:movie="http://www.sitepoint.com/movies">
      By adding this namespace definition as an attribute to a tag, we can use the prefix movie in that tag, and any tags it contains, to fully qualify our elements:
      <movie:film-types xmlns:movie="http://www.sitepoint.com/movies">
       <movie:film-type>Action</movie:film-type>
       <movie:film-type>Adventure</movie:film-type>
      </movie:film-types>

      Similarly, with the second, we can choose a different namespace "camera":
      <camera:film-types xmlns:camera="http://www.sitepoint.com/camera">
       <camera:film-type>black and white</camera:film-type>
       <camera:film-type>colour</camera:film-type>
      </camera:film-types>

      Parsers can now recognise both meanings of "film type" and handle them accordingly.
      Valid XML
      In order for an XML file to be valid, it needs at the very least to conform to the XML specification, version 1.0. This standardises exactly how your XML file is formed so that other systems can understand it. For example, XML 1.0 requires that all XML files consist of one root element; that is, a single element contains all other elements. In our music library example above, catalog is our root element, as it contains all our other elements.
      The full XML specification can be read here, although, as we'll see shortly, .NET gives you the tools to write valid XML automatically.
      XML Schemas
      While an XML file might conform to the XML specification, it might not be a valid form of a particular dialect. An XML schema lets you verify that certain elements are present, while making sure that the values presented are of the correct type.
      There are a few different specifications of schemas: XSD, DTD, and XSX. Though DTD (Document Type Definition) is the most common schema used today, XSD (XML Schema Definition) is a newer standard that's gaining acceptance, as it provides the finest grained control for XML validation.
      As XSD has many features, this introduction will concentrate on some of the simpler features you'll be able to employ.
      The first line of a schema file usually looks something like the following:
      <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
      The above defines that this file is a schema and that all the elements we're going to use for validation belong to the XML Schema namespace (to which we assign the prefix xs). You can set up additional namespaces and a number of XSD options in this tag. Check the full specification for more information.
      One of the principal validations we may want to check is whether elements are of the correct type (e.g. when we're expecting a number, we don't want to receive a string of text). This check is performed in XSD using the element tag:
      <xs:element name="foo" type="xs:integer"/>
      This means that any elements named foo must contain an integer.
      Hence, the following would validate.
      <foo>10</foo>
      However, the below code would not.
      <foo>This is some text</foo>
      You can check for a range of different types; again, see the specification for more detail.
      We can also check for a set of valid values using an enumerator. For example, our element foo may only be able to take the values "apple," "orange," and "grape." Here, we wish to define our own type, as it isn't purely a string we're after. XSD provides the simpleType to let us do this.
      <xs:element name="foo">
       <xs:simpleType>
         <xs:restriction base="xs:string">
           <xs:enumeration value="Apple"/>
           <xs:enumeration value="Orange"/>
           <xs:enumeration value="Grape"/>
         </xs:restriction>
       </xs:simpleType>
      </xs:element>

      Notice the restriction element\, which gives us a base type from which to work. As we have a list of text strings, this is set as the string type.
      So, we have basic validation on values for our elements, but what about the attributes of those elements? Well, in a similar way, we can define attributes inside an element tag:
      <xs:element name="foo">
       <xs:attribute name="colour" type="xs:string"/>
      </xs:element>

      Again, attributes can have their own types, using the simpleType elements we used for element above.
      By default, all attributes are required. However, if we don't always require an attribute to be placed on an element, we can override this default using the use="optional" attribute on the attribute element:
      <xs:attribute name="colour" type="xs:string" use="optional"/>
      A complex element is one that contains other elements, such as the "CD" element in the catalogue example given earlier:
      <cd>
         <title>The Bends</title>
         <artist>Radiohead</artist>
         <tracks>
           <track name="Street Spirit)"/>
         </tracks>
       </cd>

      Here, we need to make sure CD elements contain a title, an artist, and a tracks element. We do so using a sequence:
      <xs:element name="cd">
       <xs:complexType>
         <xs:sequence>
           <xs:element name="title" type="xs:string"/>
           <xs:element name="artist" type="xs:string"/>
           <xs:element name="tracks" type="xs:string"/>
         </xs:sequence>
       </xs:complexType>
      </xs:element>

      We can create custom types or define attributes within other elements, to help us create our hierarchical structure.
      You should notice that "tracks" is itself a complex type, as it is made up of other elements. Thus, we need to define another complexType, this time inside our tracks element. Our schema will then look like this:
      <xs:element name="cd">
       <xs:complexType>
         <xs:sequence>
           <xs:element name="title" type="xs:string"/>
           <xs:element name="artist" type="xs:string"/>
           <xs:element name="tracks">
             <xs:complexType>
               <xs:sequence>
                 <xs:element name="track">
                   <xs:attribute name="name" type="xs:string"/>
                 </xs:element>
               </xs:sequence>
             </xs:complexType>
           </xs:element>
         </xs:sequence>
       </xs:complexType>
      </xs:element>

      Of course, this just touches the surface of XSD's abilities, but it should give you a good understanding from which to begin to write your own. Then again, you can always cheat, thanks to .NET and Microsoft's XSD Inference tool, which builds a "best guess" XSD schema file from any given XML file.
      Learning to Read and Write
      Before we start getting involved with the more exciting aspects of XML, we need to know how to produce and consume XML files in .NET. .NET organises its XML classes under the System.Xml namespace, so you may want to take advantage of, and familiarise yourself with the key classes we need to use:
      • XmlTextReader: The XmlTextReader class is just one of the methods of reading XML files. It approaches an XML file in a similar way to a DataReader, in that you step through the document element by element, making decisions as you go. It's by far the easiest class to use to parse an XML file quickly.
      • XmlTextWriter: Similarly, the XmlTextWriter class provides a means of writing XML files line by line.
      • XmlValidatingReader: XmlValidatingReader is used to validate an XML file against a schema file.
      Reading an XML File In .NET
      Let's get acquainted with the XmlTextReader. XmlTextReader is based upon the XmlReader class, but has been specially designed to read byte streams, making it suitable for XML files that are to be located on disk, on a network, or in a stream.
      As with any class, the first step is to create a new instance. The constructor takes the location of the XML file that it will read. Here's how to do it in C#:
      // file
      XmlTextReader reader = new XmlTextReader("foo.xml");

      // url
      XmlTextReader reader = new XmlTextReader("http://www.sitepoint.com/foo.xml");

      // stream (here, a StringReader s)
      XmlTextReader reader = new XmlTextReader(s);

      Once it's loaded, we can only move through the file in a forward direction. This means that you need to structure your parsing routines so that they're order-independent. If you cannot be sure of the order of elements, your code must be able to handle any order.
      We move through the file using the Read method:
      while (reader.Read())
       {
         // parse our file
       }

      This loop will continue until we reach the end of our file, or we formally break the loop. We need to inspect each node, ascertain its type, and take the information we need. The NodeType property exposes the current type of node that's being read, and this is where things get a little complicated!
      An XmlReader will see the following element as 3 different nodes:
      <foo>text</foo>
      The <foo> part of the element is recognised as an XmlNodeType.Element node. The text part is recognised as an XmlNodeType.Text node, and the closing tag </foo> is seen as an XmlNodeType.EndElement node.
      The code below shows how we can output the XML tag through the reader object that we created earlier:
      while (reader.Read())
       {
         switch (reader.NodeType)
         {
         case XmlNodeType.Element:
           Console.Write("<"+reader.Name+">");
           break;
         
      case XmlNodeType.Text:
           Console.Write(reader.Value);
           break;
               
      case XmlNodeType.EndElement:
           Console.Write("</"+reader.Name+">");
           break;
         }        
       }

      Here's the output of this code:
      <foo>text</foo>
      So, what about the attributes? Well, these can be picked up in a number of ways. An attribute of type XmlNodeType.Attribute, can be parsed in the fashion shown above. More elegantly however, when we hit an XmlNodeType.Element type, we can iterate through attributes using XmlTextReader.MoveToNextAttribute:
      case XmlNodeType.Element:
         Console.Write("<"+reader.Name);
         while (reader.MoveToNextAttribute())
         {
           Console.WriteLine(reader.Name+" = "+reader.Value);
         }
       break;

      Now, if we fed in this XML:
      <foo first="1" second="2">text</foo>
      we would receive this output:
      <foo first="1" second="2">text</foo>
      Earlier, we had ignored the attributes, and would have output:
      <foo>text</foo>
      Note that, if an element does not contain any attributes, the loop is never started. This means that we don't have first to check to see whether we have attributes. That said, the number of attributes on a node can be found using the AttributeCount property.

      Validating XML in .NET
      Remember those schema files? Using the XmlValidatingReader class, we can easily validate an XML file against a schema file. However, there are a few other classes we have to use first.
      We can point the XmlValidatingReader object towards the schema files we wish to use, by filling an XmlSchemaCollection with our schema files:
      XmlSchemaCollection xsdCollection = new XmlSchemaCollection();  
       xsdCollection.Add("schemafile", "schema.xsd");

      In this example, we're using the schema contained in the file schema.xsd.
      The actual XmlValidatingReader class takes an XmlReader in its constructor. Consequently, we need to create and fill an XmlTextReader with the XML file we wish to validate:
      XmlTextReader reader;  
       XmlValidatingReader validatingReader;  
       
       reader = new XmlTextReader("foo.xml");  
       validatingReader = new XmlValidatingReader(reader);

      Then, we add our schemaCollection to the schemas we wish the validation reader to use:
      validatingReader.Schemas.Add(xsdCollection);
      If an error is found by the validator, an event is fired. We need to catch this event by creating an event handler, and code our response to the errors:
      validatingReader.ValidationEventHandler += new ValidationEventHandler(validationCallBack);  
             
      public void validationCallBack (object sender, ValidationEventArgs args)  
      {  
       Response.Write("Error:" + args.Message);  
      }

      Finally, we can validate our file using the Read method on the validating reader. We could actually read and process the nodes in the file as we did before, but, for the purposes of this example, we'll just use an empty while loop to step through the file, validating it as we go:
      while (validatingReader.Read()){}
      As errors are found during file processing, the event we catch and handle through the validationCallBack method will fire.
      Writing XML in .NET
      Now that we have a good understanding of how to read and validate an XML file, we can move on to writing XML.
      Writing XML is made very painless by the XmlTextWriter class. Again, taking a forward-only approach, we can build our XML files from different node types, which are output in order.
      To begin, we need to create an instance of the class:
      XmlTextWriter writer = new XmlTextWriter("newfoo.xml", null);
      The second parameter, which, here, is set to null, allows us to specify the encoding format to use on our XML file. Setting it to null produces a standard UTF-8 encoded XML file without an encoding attribute on the document element.
      We can now proceed to start writing elements and attributes using our code, comprised of the methods exposed in the XmlTextWriter. Let us write our earlier CD catalogue example:
      <catalog>  
      <cd>  
         <title>The Bends</title>  
         <artist>Radiohead</artist>  
         <tracks>  
           <track name="Street Spirit "/>  
         </tracks>  
       </cd>  
      </catalog>

      Our first line is the element catalog. We use the WriteStartElement method to write this to the writer:
      writer.WriteStartElement("catalog");
      Notice that we don't want to close this element until we've written our CD elements. Thus, the next node we wish to add is an opening CD element:
      writer.WriteStartElement("cd");
      We now have a title element (<title>The Bends</title>). As before, we write a start element, but this type will differ because we have a specific value we wish to use. As we have no attributes on the title element, we can use the WriteElementString method:
      writer.WriteElementString("title", "The Bends");  
      writer.WriteElementString("artist", "Radiohead");  
       
      writer.WriteStartElement("tracks");

      Now we've reached an element, track, with an attribute, name. We first need to write the start of the element, then write the attributes, and finally, close our element:
      writer.WriteStartElement("track");  
      writer.WriteAttributeString("name", "Street Spirit");  
       writer.WriteEndElement();

      Notice how we don't need to say which element we wish to close, because the writer will automatically write the closing tag for the last-opened element, which, in this case, is track.
      We can now close our remaining elements in the same fashion:
      writer.WriteEndElement();  
      writer.WriteEndElement();

      Finally, we need to "flush" the writer, or, in other words, to output the information we've requested to our XML file, then close the writer to free our file and resources:
      writer.Flush()  
       writer.Close()

      Summary
      So completes this introduction to XML and its use within .NET. Hopefully, the world of XML no longer seems as intimidating as you might have originally thought, and you're now ready to harness its power for your next project.