Friday, March 4, 2011

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.

 

1 comment: