Server-Side XML in ASP

By Adam S. Cartwright

With the upcoming release of Internet Explorer 5.0, it is much easier to use XML in Web applications. Here is some information on how to harness the power of the updated XML Document Object Model (DOM) on the server to parse and use XML data in ASP applications.

The Need

The ability to parse and use XML on the server provides developers with a whole new world of functionality. As the widespread use of XML increases, so does the need for manipulating XML on the server. To demonstrate server-side XML in ASP, I will use the syndicated XML version of the Scripting News, a Web site of news and commentary from the cross-platform scripting community ( http://www.scripting.com). I will show how to create a simple ASP page that displays the date of the last issue of the Scripting News and the number of headlines it contains, then I will display all of the current headlines with their corresponding URL links.

The Document Object Model

The updated XML Document Object Model in Internet Explorer 5.0 (IE 5.0) fully supports the programming interfaces described in the W3C Document Object Model Core (Level 1) recommendation. It also includes a number of new methods for supporting related XML technologies, such as XSL, XSL Pattern Matching, namespaces, data types, and schemas. The DOM is in essence an XML parser; the DOM exposes the XML document as a tree structure that is easy to navigate and use.

There are two groups of DOM programming interfaces, as defined by the W3C Core recommendation. The first group defines interfaces that are needed to write applications that use and manipulate XML documents. The second group defines interfaces to assist developers and make it easier to handle XML. This second group of interfaces is for convenience and is not essential for using XML.

Using the DOM on the server in an ASP application is quite easy, but requires that IE 5.0 be installed on the server itself. This is necessary due to the number of supporting components installed with IE. Once IE is installed on the server, all you have to do in ASP is create the DOM object as such:



<% Set objXML = Server.CreateObject("Microsoft.XMLDOM") %>


XML on the Server

Once you have created the DOM object on the server, you can build your own XML document or load an existing document. When loading a document, you have the option of loading a string of XML text, or opening a XML document and loading the contents. For our example, we will assume that our server has a local copy of the most recent Scripting News XML document. Before loading the document, you should set the async property of the DOM object to "false." This tells the DOM object not to perform an asynchronous download of the XML document. This is important, since immediately after we load the document we are going to start using its contents. If the contents are not all loaded at that time, we may get an error when we try to access it.


 <%
 Set objXML = Server.CreateObject("Microsoft.XMLDOM")

 objXML.async = False

 objXML.Load (Server.MapPath("mostRecentScriptingNews.xml"))
 %>

Let's look at the actual XML document that we are loading:


 <?xml version="1.0"?>

 <!DOCTYPE scriptingNews SYSTEM
      "http://www.scripting.com/dtd/scriptingNews.dtd">
 <scriptingNews>
   <header>
     <copyright>Copyright 1997-1999 UserLand Software, Inc.
     </copyright>
     <scriptingNewsVersion>1.0</scriptingNewsVersion>

     <pubDate>Wed, 03 Mar 1999 08:00:00 GMT</pubDate>
     <lastBuildDate>Thu, 04 Mar 1999 03:37:03 GMT</lastBuildDate>
   </header>
   <item>
     <text>Wired: A Linux Car Stereo! Wow.</text>

     <link>
       <url>http://www.wired.com/news/news/technology/ ...
            story/18236.html
       </url>
       <linetext>A Linux Car Stereo</linetext> 
     </link>
   </item>

   ...
   <item>
     <text>According to News.com, Hewlett-Packard will offer
           customers storage and computing on a rental basis.
     </text>
     <link>
       <url>http://www.news.com/News/Item/ ...
            0,4,33202,00.html?st.ne.fd.mdh
       </url>

       <linetext>According to News.com</linetext>
     </link>
   </item>
 </scriptingNews>


The DOM object exposes a parseError object that contains information about the last parsing error. This object is extremely helpful for debugging and error handling within the ASP page. After loading the XML document, it's a good idea to check the parseError object for any errors before continuing.


 <%
 If objXML.parseError.errorCode <> 0 Then
	 handle the error
 End If
 %>

Fortunately, the parseError object provides us with a lot of valuable information about the error:

errorCode
Property Description
The error code
filepos The absolute file position in the XML document containing the error
Line The line number in the XML document where the error occurred
linepos The character position in the line containing the error
reason The cause of the error
srcText The data where the error occurred
URL The URL of the XML document containing the error

In our Scripting News example, the parseError object takes on even greater meaning since the XML document is referencing a Document Type Definition (DTD) file. In this case, not only must the XML document be well formed, it must also be valid against the DTD in order to be error free. It is good practice to always check the parseError object after loading XML.

Now that we have a well-formed and valid document in our DOM object, let's look in the document to see what we have. The DOM exposes a number of useful methods to determine exactly what is in an XML document. Because the DOM exposes the contents of the document as a tree of nested nodes (a node consists of an element and any nested subelements), we will actually end up creating a series of node objects in order to manipulate the data. We're going to use the getElementsByTagName method to get a list of the elements, or nodes, in the document.

Our first goal is to discover the publishing date for our copy of Scripting News. By examining the DTD we know that this information is stored in the pubDate node. A simple way to access the contents of this node is first to create a node list object of all of the nodes within the XML document, then loop through it until we find the pubDate node. Because the DTD dictates that the pubDate node cannot contain any subnodes, we can use the text property to immediately pull out the contents of the node.


 <%
 Set objXML = Server.CreateObject("Microsoft.XMLDOM")
 Set objLst = Server.CreateObject("Microsoft.XMLDOM")
 objXML.async = False
 objXML.Load (Server.MapPath("mostRecentScriptingNews.xml"))
 If objXML.parseError.errorCode <> 0 Then
	 handle the error
 End If

 Set objLst = objXML.getElementsByTagName("*")

 For i = 0 to (objLst.length - 1)

    If objLst.item(i).nodeName = "pubDate" Then
      StrDate = objLst.item(i).text
      Exit For
    End If

 Next
 %>

Notice in the above example we passed an "*" to getElementsByTagName. This returned a node list object containing all of the elements, or nodes, in the document. Because we have the DTD and can gain from it the exact position of the pubDate node, we could have addressed it directly using its item number. However, looping through a document, as we did in the above example, is actually quite efficient since the node list is a collection.

Now that we have the publish date, let's look at how to find the number of headlines in the document. Once again, we can draw from our knowledge of the DTD and recall that the headlines are stored in "item" nodes. There is one item node per headline in the document. We could use another loop, like we did above, and increment a counter each time we encounter an item node. However, there is a better way to retrieve this information, using another method exposed in the DOM.

As in the example above, all we need to do is create a node list object containing all of the item nodes. Then we'll use the length property to find out how many nodes are in the node list object or, in other words, the number of headlines in the document.


 <%
 Set objLst = objXML.getElementsByTagName("item")

 strNoOfHeadlines = objLst.Length
 %>

Most likely we would also like to display some of this information on our ASP page. The next example shows how we could list the headlines and their URLs in our ASP page by looping through the node list of headlines.

 <%
 Set objXML = Server.CreateObject("Microsoft.XMLDOM")
 Set objLst = Server.CreateObject("Microsoft.XMLDOM")
 Set objHdl = Server.CreateObject("Microsoft.XMLDOM")

 objXML.async = False
 objXML.Load (Server.MapPath("mostRecentScriptingNews.xml"))

 If objXML.parseError.errorCode <> 0 Then
	 handle the error
 End If

 Set objLst = objXML.getElementsByTagName("item")

 noOfHeadlines = objLst.length
 %>

 <HTML><BODY>
 <H1>Scripting News Headlines</H1>

 <%
 For i = 0 To (noOfHeadlines - 1)

  Set objHdl = objLst.item(i)

  Response.Write("<a href=""" & _
                  objHdl.childNodes(1).childNodes(0).text & _
                  """>" & objHdl.childNodes(0).text & _
                  "</a><br>")

 Next
 %>

 </BODY></HTML>


Conclusion

With a little information about the structure of the XML document and by harnessing the power of the DOM, you can easily parse the XML document on the server in ASP and send whatever results you like to the client. This example is browser neutral and would work in almost all Web browsers.

Next time I will discuss how to use XSL on the server side to display complex XML documents on the client.

About the Author

Adam S. Cartwright is a software consultant in Denver, Colorado, specializing in advanced Internet technologies such as XML, ADSI, DHTML, and ASP. Adam will spoke on XML technologies at the 1999 Spring Professional ASP Developers Conference (http://asp99.nextmeeting.com).



Comments

  • It's been a persevering week on account of enlighten apparatus exit|motor coach fissure online

    Posted by Stoompota on 06/26/2013 01:36pm

    Just got an update today fromTory [url=http://andysdm.com/]coach outlet factory[/url] Burch about their Fall Sale. A variety of new items [url=http://andysdm.com/]coach outlet[/url] were [url=http://andysdm.com/]coach outlet [url=http://andysdm.com/]wholesale coach handbags[/url] online store[/url] recently added to the Sale. If you have already checked it out, head over to ToryBurch.com. Visitors save up to 60% off on Handbags and get Free Shipping on orders of $!50 or more. Valid Only at ToryBurch.com. Sale Ends 11:59pm, October 31, 2009.

    Reply
  • plus size lingerie

    Posted by ivas on 06/18/2013 02:02am

    There is also a largest site where Sexy lingerie, seductive lingerie, plus size ngerie, corsets, bustier, baby dolls, teddy’s, club wear, wigs, eyelashes are available. corsets club wear seductive lingerie plus size lingerie

    Reply
  • Wonderful Site You Have Here!

    Posted by FronginiovaJA on 05/21/2013 12:38am

    I used to read a great deal of books but now I surf the internet looking for really good blogs like this one to read. this was a good read thanks!

    Reply
  • interested in pay day loans uk bad credit

    Posted by Nuptsmeashhem on 04/29/2013 11:09am

    This and then forces a Canadian small business owner and financial manager to assess options you don�t necessarily should consider, i personally instant loans uk. As a result we have an increase in on the net application for financial assistance a lot of borrowers today has the service to apply 24/7 This list was created for suggestions and information for the person in will need, not the needy as well as greedy Concurrently, I purchased your $20,000, totally loaded truck (a good chunk of change for your vehicle within 1991 宝贝价格

    Reply
  • cheap hats

    Posted by xxds5my on 04/01/2013 06:07am

    [url=http://snapbackhatwholesale.webs.com]snapback hats wholesale[/url] snapback hats wholesale d sicr [url=http://snapbackhatwholesale.webs.com]wholesale snapbacks[/url] wholesale snapbacks q bhxu[url=http://snapbackswholesalezone.webs.com]snapbacks wholesale[/url] snapbacks wholesale d gzmi[url=http://snapbackhatwholesale.webs.com]wholesale beanies[/url] wholesale beanies a qkap[url=http://snapbackswholesalezone.webs.com]snapbacks wholesale[/url] snapbacks wholesale t uvrv[url=http://goodsnapbackhatscheap.webs.com]snapback hats cheap[/url] snapback hats cheap e qjhm [url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping u hiso [url=http://cheaphatsmall.webs.com]snapback hats cheap[/url] snapback hats cheap o spmh[url=http://snapbackswholesalezone.webs.com]snapbacks wholesale[/url] snapbacks wholesale u soyu[url=http://snapbackswholesalezone.webs.com]snapback wholesale[/url] snapback wholesale o zumr[url=http://cheaphatsmall.webs.com]snapback hats cheap[/url] snapback hats cheap p qguo[url=http://wholesalefittedhat.webs.com]wholesale fitted hats[/url] wholesale fitted hats j awzr [url=http://cheaphatsmall.webs.com]cheap snapbacks[/url] cheap snapbacks v otyq [url=http://snapbackswholesalezone.webs.com]fitted hats wholesale[/url] fitted hats wholesale o hyqa[url=http://snapbackhatwholesale.webs.com]snapback hats wholesale[/url] snapback hats wholesale q cnbk[url=http://cheapsnapbackshat.webs.com]cheap hats[/url] cheap hats h tuuu[url=http://snapbackswholesalezone.webs.com]snapback hats wholesale[/url] snapback hats wholesale i hmaf[url=http://cheapsnapbackshat.webs.com]cheap hats online[/url] cheap hats online f bcsf

    Reply
  • womens sexy clothes

    Posted by Fishnetyv1071 on 03/29/2013 09:02am

    http://sexycostumesboutique.webs.com - Naughty School Girl UniformIt is for this reason that I have taken it upon myself to write this informative Man's Guide to Women's Lingerie" Complement Your AssetsEach of us have features that others find attractive http://sexycostumesboutique.webs.com - Nurse CostumesIn this case, you can’t choose a gift base on his personalitylinge? meaning washables http://sexycostumesboutique.webs.com - Naughty School Girl UniformIt includes costumes for adults, kids as well as mascot costumes and provides party makeup supplies, accessories, decorations and props What kind of lingerie to buy, what size, what color - how is a man to know? Here is a little introduction to assist you when selecting lingerie for that special someone http://SexyTeddies.webs.com - sexy lingerie teddiesThis type of lingerie is actually carefully crafted to make plus size women appear slimmer than ever Meanwhile, for your new neighbor, observe a bit http://sexystockings.webs.com - Fishnet BodystockingWhen you are buying a bra and panty set, always check out what she has in her drawer beforehand and definitely notice the size - of both the bra and panties7

    Reply
  • white lace lingerie

    Posted by Fishnetto1054 on 03/29/2013 08:45am

    http://discounteroticlingerie.webs.com - Erotic LingerieThey have created all the latest in dreamgirl style including the most comprehensive ones One of the most popular types of lingerie is the baby doll lingerie set http://SexyChemise.webs.com - Lace Chemise  They will be able to give you a clearer idea of what styles of lingerie she likes to wear so you don’t make any mistakes, but also they will know which companies she prefers This means a woman can enhance the lower part of the body by a loose garment with a tight fit across the waist and the bosom, to bring a combination of a slim top and an emphasized nether region http://sexylingerieshops.webs.com - Candy Lace lingerie1 He was so pleased with the system that he had it installed in all his restaurants http://sexycostumesus.webs.com - cop costumeIt is for this reason that I have taken it upon myself to write this informative Man's Guide to Women's Lingerie" Complement Your AssetsEach of us have features that others find attractive http://babydolllingeriee.webs.com - sheer babydollsSome websites give detail description including the percentage of components of the material it was made of Many teddies come with garter belts attached, adding endless possibilities for some naughty, bad little girls' psychopathic imagination to run wild with

    Reply
  • Sexy Nurse Lingerie

    Posted by Fishnetec1066 on 03/29/2013 07:45am

    http://sexystockings.webs.com - Fishnet BodystockingOften, wholesalers, distributors or even manufacturers offer discount pricing for quantity purchases8 http://sexystockings.webs.com - Sexy BodyStockingsThey have lingerie from bustiers, corsets and babydollsIf you happen to be really hunting for lingerie to spice up your love life, be sure to visit Frederick's of Hollywood (accessible online) http://sexylingeriecostumese.webs.com - Lingerie CostumesLet’s look a bit deeper into the colors Perhaps an afternoon can be allotted to the group to design, shop and decorate http://lingeriemall.webs.com - pink lace lingerieWhen looking for lingerie, try to take into account what she likes Let the environment be tasteful, yet celebratory http://sexycostumesa.webs.com - Maid LingerieThis company grew for 35 years and had continuously offered a wide array of products such as sexy costumes, fetish wear, plus size costumes, sexy lingerie and even menIf you happen to be really hunting for lingerie to spice up your love life, be sure to visit Frederick's of Hollywood (accessible online)

    Reply
  • http://www.oakleysunglassesoutc.com/ njtiom

    Posted by http://www.oakleysunglassesoutc.com/ Mandynzr on 03/29/2013 05:46am

    In fact, if you can wait Jingjiang class cruiser, ghd sale there is greater redundancy on the front against the German, and now ... Oh, really soldiers line insurance forward to ah! Insurance is risk, but the results are still very desirable. ghd hair straightener do not know what the Longwei level or Jingjiang level, cheap ghd only know that these warships political chips ... group security, sometimes an upper. As you land aides, ghd australia have to remind you, in it, you've wasted a lot of energy and money ... quiet said. Tan Yankai turned to quiet said: the Wenyuan brother, you know what power it? Quiet also hear a moment, shook his head confused. Tan Yankai shook his head and said: In fact, your heart is to understand, in these troubled times, into the hands of the forces of power! The new army, the Northern Navy case, no power even if the ghd hair straightener military minister can they do?

    Reply
  • wholesale snapbacks

    Posted by xxds6de on 03/29/2013 01:51am

    [url=http://cheapsnapbackshat.webs.com]cheap hats for sale[/url] cheap hats for sale f dcax [url=http://snapbackswholesalezone.webs.com]snapback hats wholesale[/url] snapback hats wholesale z itle[url=http://cheapsnapbacksforsalezone.webs.com]snapback hats cheap[/url] snapback hats cheap x ervm[url=http://cheapsnapbacksforsalezone.webs.com]snapback hats cheap[/url] snapback hats cheap z hude[url=http://snapbackswholesalezone.webs.com]snapback hats wholesale[/url] snapback hats wholesale n yreo[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks for sale[/url] cheap snapbacks for sale w neda [url=http://bestbaseballcap.webs.com]wholesale snapback caps[/url] wholesale snapback caps m jjzl [url=http://cheapsnapbacksforsalezone.webs.com]snapback hats cheap[/url] snapback hats cheap e ccxp[url=http://cheapsnapbackshat.webs.com]cheap snapbacks hats[/url] cheap snapbacks hats k jkcj[url=http://bestbaseballcap.webs.com]wholesale baseball caps[/url] wholesale baseball caps h koyg[url=http://bestbaseballcap.webs.com]hats wholesale[/url] hats wholesale h wfkw[url=http://snapbackhatwholesale.webs.com]wholesale snapbacks[/url] wholesale snapbacks f dzaz [url=http://snapbackhatwholesale.webs.com]snapback hats wholesale[/url] snapback hats wholesale i ncfc [url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks online[/url] cheap snapbacks online f ycwv[url=http://goodsnapbackhatscheap.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping y dybo[url=http://bestbaseballcap.webs.com]wholesale hats[/url] wholesale hats o ecxt[url=http://cheapsnapbackshat.webs.com]cheap snapbacks hats[/url] cheap snapbacks hats x mswl[url=http://snapbackswholesalezone.webs.com]hats wholesale[/url] hats wholesale x cuqu

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • IBM Worklight is a mobile application development platform that lets you extend your business to mobile devices. It is designed to provide an open, comprehensive platform to build, run and manage HTML5, hybrid and native mobile apps.

  • Protecting business operations means shifting the priorities around availability from disaster recovery to business continuity. Enterprises are shifting their focus from recovery from a disaster to preventing the disaster in the first place. With this change in mindset, disaster recovery is no longer the first line of defense; the organizations with a smarter business continuity practice are less impacted when disasters strike. This SmartSelect will provide insight to help guide your enterprise toward better …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds