ASP vs ASP.NET: XML

Introduction

XML is commonly used these days for various purposes: data storage, maintaining information that could be kept in memory (but need long-term storage), configuration information, web services, and so on. Of course, there needs to be a means to read this information, and to write it if necessary.

This article starts with a (very) brief introduction to XML and its format. It then mentions the two main XML parsers available for the ASP and ASP.NET platforms. Finally, you get to see some code which shows the difference between the two platforms when it comes to reading and writing XML.

XML Basics

For those of you who are not familiar with XML (unlikely, considering how much of a buzzword it is these days!), it is a simple, text-based format for storing information. It can be either stored in memory for a short time, or written to a file and read later. Similar to HTML, an XML document is made up of elements, attributes, and values. Elements are also called tags, and can contain other elements. Elements may also have attributes, which are information ABOUT the element, not information contained in the element itself. Finally, elements, besides containing other elements, may also contain content.

Following is a listing of a simple XML document:

< ?xml version="1.0"?>
<rootelement>
  <someelement>Some random text
</rootelement>

Well, that’s the XML crash course. If you need to know more about XML, I recommend the W3 Schools’ XML Tutorial.

Parsing XML

Now it is time to talk about parsing XML. You may have noticed in the sample above that the elements, along with their attributes, are enclosed in < and >. Each element enclosed with those angle brackets form what is usually called a tag, a tag representing the element. When reading and writing XML through program code, it would be very tedious to have to deal with those angle brackets, wouldn’t it? And to locate attributes for a certain element and to determine whether an element contains other elements…It would get very complicated. In comes the parser. In a general sense, a parser simplifies reading and writing text to the point where you don’t have to worry about delimiting characters, or properly nesting elements. When working with XML in program code, a parser makes things much easier.

ASP does not provide a built-in XML parser, but it can use the MSXML parser which is installed along with recent versions Internet Explorer. The .NET framework has a System.Xml namespace which is full of useful classes and functions to use when working with XML, so ASP.NET is covered already.

Now that the stage is set, it’s time to look at some code.

Writing XML

ASP

Dim objDom, objRoot, blnFileExists, objEl, objPI
Set objDom = Server.CreateObject("Microsoft.XMLDOM")

'Load method returns true if the file was loaded, false if not
blnFileExists = objDom.Load("file.xml")

'Check to see whether the file was loaded
If blnFileExists Then
  'File exists, so just get the document's existing root element
  Set objRoot = objDom.DocumentElement
Else
  'File does not exist; so create and append a root element
  Set objRoot = objDom.CreateElement("rootElement")
  objDom.AppendChild objRoot
End If

'Create an element, give it a value, and append to the root element
Set objEl = objDom.CreateElement("someElement")
objEl.Text = "Some random text"
objRoot.AppendChild objEl

'If the file did not already exist
If blnFileExists = False Then
  'Create the XML processing instruction
  Set objPI = objDom.CreateProcessingInstruction("XML", "version='1.0'")

  'Append the processing instruction object to the XML document,
  'BEFORE any of the other items
  'Appears as: < ?xml version="1.0"?>
  objDom.InsertBefore objPI, objDom.ChildNodes(0)
End If

'Save the XML document
objDom.Save "file.xml"

Note the extra steps ASP has to go through besides actually adding an element to the document. Additionally, just to add an element, you need to create one, give it a value, and finally append it to the document. Three steps. Not the neatest way to do it.

ASP.NET

Imports System.Xml

'Create an object to write XML to a given file
Dim objWriter As XmlTextWriter = New XmlTextWriter("file.xml")

'Processing instruction added automatically
objWriter.WriteStartDocument()

'Add the root element first
objWriter.WriteStartElement("rootElement")

'Add an element with some text
objWriter.WriteElementString("someElement", "Some random text")

'Close the root element
objWriter.WriteEndElement()

'End the document - does not close the root node for you!
objWriter.WriteEndDocument()

'Done, so output XML to the file and close it
objWriter.Flush()
objWriter.Close()

Not too many steps here, and fairly straightforward.

Reading XML

ASP

Dim objDom, objRoot, objEl, strElText

'Create an object to contain the XML file in memory
Set objDom = Server.CreateObject("Microsoft.XMLDOM")

objDom.Load("file.xml")

'Get the document's root element
Set objRoot = objDom.DocumentElement

'Get access to the desired element
Set objEl = objRoot.SelectSingleNode("someElement")

'Get the desired node's first child node, which contains
'the text, then get the text from that child node
strElText = objEl.ChildNodes(0).Text

The XML reading routine in ASP starts by creating a Microsoft.XMLDOM object to hold the contents of a given XML file, which is then loaded into memory. Next step is to get a reference to a named node within the root node. The desired node actually has a child node that contains the text, so get the current node’s first child node, and then retrieve that node’s text value.

ASP.NET

Imports System.Xml

'An object to contain the XML in memory
Dim objReader As XmlDocument = New XmlDocument()

'Load the XML file
objReader.Load("file.xml")

Dim strElText As String

'Nice and simple, straight to the desired node
Dim node As XmlNode = objReader.SelectSingleNode("/rootElement/someElement")

'Get the text from the selected node
strElText = node.InnerText

Similar to Classic ASP, ASP.NET uses an object (in this case, XmlDocument) to load the contents of an XML file into. ASP.NET can just use an XPath expression to retrieve a single node, or even a group of nodes, at the end of a given path through an XML file. Explaining XPath is beyond the scope of this article, so I would suggest reading the W3Schools’ XPath tutorial for more details on what XPath is and how it works. It’s then a simple matter of using the .InnerText property to retrieve the content of the current node.

Conclusion

So, reading and writing XML is done very similarly between ASP and ASP.NET. There are slight syntax differences, really just in the objects and functions being used, but the overall code flow is nearly the same.

When writing XML, ASP requires three steps to go through to create an element, give it a value, and add it to the document. ASP.NET can do it all in one line, which is much cleaner.

I would also like to point out that the ASP.NET method of reading XML is slightly more readable and intuitive than the Classic ASP method. With ASP.NET, you just need to use an XPath expression to get at the node you want, where Classic ASP needs 3 steps to retrtieve a single element, and they are not as intuitive.

Make a Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>