Discussions in Asp.Net are always incomplete without first discussing the “namespaces” and “classes” provided by the .Net framework. We need to understand which namespaces and classes will be in use.
The namespace System.xml provides the basic support for processing XML in Asp.Net. When I say support, I mean the classes and its methods that will give us the ability to write and read data.
The two primary classes we will use in our examples and in this article are XmlWriter and XmlTextReader respectively.
XmlWriter
The XmlWriter class is a base class that provides a forward-only, read-only process to generate XML stream. Let me explain. It provides methods to write data in an XML document. Good we know it, since in our example, we are using various methods of this class to write data and it is simple.
XmlTextReader
The XmlTextReader is the next class we will use to read the data from an XML document. Again, this class has some very nice properties and methods. I'll not discuss all the methods in this article, but if you find any interesting method, that you think I should have included in this article, then please let me know.
Write XML using XmlWriter
Let's see these classes and its methods in action. Open Visual Studio, from the file menu select new website, and choose the language of your choice.
You can process these functions either on a button click event or on the page load event. In the code behind section, add the below code to write data in an XML file.
using System; using System.Xml; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { using (XmlWriter xWr = XmlWriter.Create(Server.MapPath("library.xml"))) { xWr.WriteStartDocument(); xWr.WriteStartElement("Library"); xWr.WriteStartElement("List"); // ADD FEW ELEMENTS. xWr.WriteElementString("BookName", "Computer Architecture"); xWr.WriteElementString("Category", "Computers"); xWr.WriteElementString("Price", "125.60"); xWr.WriteEndElement(); // CLOSE LIST. xWr.WriteEndElement(); // CLOSE LIBRARY. xWr.WriteEndDocument(); // END DOCUMENT. // FLUSH AND CLOSE. xWr.Flush(); xWr.Close(); // SHOW A MESSAGE IN A DIV. div_xml.InnerText = "File created."; } } }
Option Explicit On Imports System.Xml Partial Class _Default Inherits System.Web.UI.Page Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Load ' CREATE A NEW XML FILE AND INSERT DATA. Dim xWr As XmlWriter xWr = XmlWriter.Create(Server.MapPath("library.xml")) Using xWr With xWr .WriteStartDocument() .WriteStartElement("Library") .WriteStartElement("List") ' ADD FEW ELEMENTS. .WriteElementString("BookName", "Computer Architecture") .WriteElementString("Category", "Computers") .WriteElementString("Price", "125.60") .WriteEndElement() ' CLOSE LIST. .WriteEndElement() ' CLOSE LIBRARY. .WriteEndDocument() ' END DOCUMENT. .Flush() : .Close() ' FLUSH AND CLOSE. 'SHOW A MESSAGE IN A DIV. div_xml.InnerText = "File created." End With End Using End Sub End Class
In our form load event, we have place the code to write data. The create() method will create a new instance of XmlWrite class. It takes a parameter in the form of an outputFileName.
C#
using (XmlWriter xWr = XmlWriter.Create(Server.MapPath("library.xml")))
Vb.Net
Dim writer As XmlWriter writer = XmlWriter.Create(Server.MapPath("library.xml"))
Method WriteStartDocument() and WriteEndDocument()
Immediately after creating an instance, we will declare a method called WriteStartDocument(). This method opens data writing process which is later closed by WriteEndDocument(). You must declare these two methods to start the entire process of writing in an XML file.
There are numerous other methods that we are not using, since it beyond the scope of this article. We may define each of the methods in other articles as well.
Method WriteStartElement() and WriteEndElement()
The tags which form the outer shell or section of an XML will be written using WriteStartElement(), and tag will be closed at the end with WriteEndElement().
<Library> <!-- THE FIRST TAG -->
more tags with element…
</Libraty>
In our example we have two tags, the first tag is the Library, followed the second tag List. It is very important to remember that these tags are case sensitive, and must declare and used carefully.
Method WriteElementString()
We have created the instance, declared start and end documents, followed by creating the two tags. Now we add actual data into the file. This is done using the WriteElementString() method.
C#
xWr.WriteElementString("BookName", "Computer Architecture");
Vb.Net
.WriteElementString("BookName", "Computer Architecture")
This method takes two parameters, as you can see. The first parameter is the local name or simply the name of the element and second parameter is the value of the element.
<BookName>Computer Architecture</BookName>
You can write it more specifically by declaring methods individually.
C#
xWr.WriteStartElement("BookName"); xWr.WriteString("Asp.Net Black Book"); xWr.WriteEndElement();
Vb.Net
xWr.WriteStartElement("BookName") xWr.WriteString("Asp.Net Black Book") xWr.WriteEndElement()
Few interesting and useful methods which we have not included in our example, but worth describing.
Method WriteComment()
If you have checked our Library.xml file we might have noticed a comment saying “<! -- Last edited by https://www.encodedna.com --> Comments are very useful for describing a class, a procedure or a function. Similarly, always add comments to highlight or describe the usage of a document and its contents.
Add the below line before the first tag (“Library”) is created. You can add it anywhere you wish.
.WriteComment("Last edited by https://encodedna.com")
Read XML using XmlTextReader
We have written data in an XML file using various methods. Now let us check the contents of the file. To read the contents we will use XmlTextReader class, which provides fast and forward-only access to XML data.
XmlTextReader class too, has a huge collection of methods and properties used for various purposes. Out of many, we have used few methods and a property in our example.
Before opening the XML file for reading, we will checked if the exists in our folder. We have added another namespace in the beginning of our code.
C#
using System.IO;
Vb.Net
Imports System.IO
The System.IO namespace contains methods and properties for Input and Output operations like reading and writing a file. Using one of its methods, we will check if the defined XML file exists in the folder.
File.Exists()
<!DOCTYPE html>
<html>
<head>
<title>Read and Write Data in XML Using Asp.Net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="div_xml" runat="server"></div>
<br />
<input id="View" value="View XML" type="button"
onserverclick="ViewXML" runat="server" />
</div>
</form>
</body>
</html>
We have added a button control in our form. Upon clicking, the button will call a procedure named “ViewXML” written in the Code behind section.
public void ViewXML(object sender, EventArgs args) { if (File.Exists(Server.MapPath("library.xml"))) { xml.InnerText = ""; XmlTextReader xlRead = new XmlTextReader(Server.MapPath("library.xml")); while (xlRead.Read()) { xlRead.MoveToElement(); div_xml.InnerHtml = div_xml.InnerHtml + "<br />" + xlRead.Name + " " + xlRead.Value; } xlRead.Close(); xlRead = null; } }
Public Sub ViewXML(ByVal sender As Object, ByVal args As EventArgs) ' READ THE XML DATA USING "XmlTextReader". If File.Exists(Server.MapPath("library.xml")) Then div_xml.InnerText = "" Dim xlRead As New XmlTextReader(Server.MapPath("library.xml")) While xlRead.Read() xlRead.MoveToElement() div_xml.InnerHtml = div_xml.InnerHtml & "<br />" & xlRead.Name & " " & xlRead.Value End While xlRead.Close() : xlRead = Nothing End If End Sub
The above code has a basic function that checks, opens, reads and displays the XML contents in HTML format (using a DIV element).
However, when you check the output, it shows every little piece of data that is readable, but in an undesirable format.
We want to view the data in a format that is understandable by our users and everyone who is checking these data online.
It is a bit tricky. I'll explain this.
Clean HTML format
While browsing through each element, we need to check the type of element and accordingly the values associated with the elements. This way we can avoid displaying unnecessary elements.
In this example, I have three main elements and values. The elements are the BookName, Category and Price.
Modify the procedure ViewXML with code written below.
public void ViewXML(object sender, EventArgs args)
{
if (File.Exists(Server.MapPath("library.xml")))
{
div_xml.InnerText = "";
// READ THE XML DATA USING "XmlTextReader".
XmlTextReader xlRead = new XmlTextReader(Server.MapPath("library.xml"));
while (xlRead.Read())
{
xlRead.MoveToElement();
switch (xlRead.NodeType)
{
case XmlNodeType.Element:
if (xlRead.Name == "BookName")
{
div_xml.InnerHtml = div_xml.InnerHtml + "<br />" + xlRead.Name + ": " + xlRead.ReadString();
}
if (xlRead.Name == "Category")
{
div_xml.InnerHtml = div_xml.InnerHtml + "<br />" + xlRead.Name + ": " + xlRead.ReadString();
}
if (xlRead.Name == "Price")
{
div_xml.InnerHtml = div_xml.InnerHtml + "<br />" + xlRead.Name + ": " + xlRead.ReadString();
}
break;
}
}
xlRead.Close();
xlRead = null;
}
}
Public Sub ViewXML(ByVal sender As Object, ByVal args As EventArgs)
If File.Exists(Server.MapPath("library.xml")) Then
div_xml.InnerText = ""
' READ THE XML DATA USING "XmlTextReader".
Dim xlRead As New XmlTextReader(Server.MapPath("library.xml"))
While xlRead.Read()
xlRead.MoveToElement()
Select Case xlRead.NodeType
Case XmlNodeType.Element
If Trim(xlRead.Name) = "BookName" Then
div_xml.InnerHtml = div_xml.InnerHtml & "<br />" & xlRead.Name & ": " & xlRead.ReadString
End If
If Trim(xlRead.Name) = "Category" Then
div_xml.InnerHtml = div_xml.InnerHtml & "<br />" & xlRead.Name & ": " & xlRead.ReadString
End If
If Trim(xlRead.Name) = "Price" Then
div_xml.InnerHtml = div_xml.InnerHtml & "<br />" & xlRead.Name & ": " & xlRead.ReadString
End If
End Select
End While
xlRead.Close() : xlRead = Nothing
End If
End Sub
The output this time is readable and much cleaner than before.
I could have go on and on describing the numerous properties and methods in the above mentioned classes. However, it is beyond the scope of this article. Meanwhile, you can try with few more methods like XmlNodeType.XmlDeclaration, XmlNodeType.Comment and XmlNodeType.Text. Also, try some its properties like the BaseURI, AttributeCount and HasValue.