MSXML, concluded

This article, the third of three parts, explains what MSXML is and how to access an XML document using JavaScript. It is excerpted from chapter 10 of XML DeMYSTified, written by Jim Keogh and Ken Davidson (McGraw-Hill/Osborne, 2005; ISBN: 0072262109).

Contributed by
Rating: 4 stars4 stars4 stars4 stars4 stars / 5
March 30, 2006
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

Select, Extract, Delete, and Validate

So far in this chapter, you’ve learned how to insert one XML document into another. In addition to this, you’ll need to select, extract, delete, and validate information contained in an XML document.

We’ll explore how to perform these common tasks in this section. First we’ll show you how to create an HTML page that enables you to execute each of these tasks. In a real-world application, of course, these tasks would be built into your application.

Here’s the HTML page we’ll use for these examples:

<tr valign="top">
<td colspan="2" nowrap>
<a href="#" onclick="SelectArtist(document.all('artist').value);
   return false;">Select Artist:</a>
   <input type="text" id="artist" value="U2" size="15"><br>
<a href="#" onclick="DisplayTitles();
    return false;">Display Titles</a><br>
<a href="#" onclick="DeleteNodes(
    document.all('upcDelete').value); return
    false;">Delete Nodes w/UPC:</a>
  
<input type="text" id="upcDelete"
        value="75678367229" size="15"><br>
<a href="#" onclick="ValidateDocument();
       
return false;">Validate Document</a>
</td>
</tr>

The SelectArtist() Function— Filtering an XML Document

The SelectArtist() function is used to display information about an artist’s CDs by entering the name of the artist and then having the SelectArtist() search and display related information about the artist’s CDs. Here’s the SelectArtist() function:

function SelectArtist(artist)
{
   var objNodes = objXML.selectNodes(
        
"/catalog/cd[artist='" + artist + "']")
   if(objNodes.length == 0)
   {
     
alert("Could not find artist with name " + artist);
      
return;
   }
   var root = objXML.documentElement;
   var cdList = root.selectNodes("/catalog/cd");
   cdList.removeAll();
   for(var i=0; i < objNodes.length; i++)
   {
     
root.appendChild(objNodes.item(i));
   }
   document.all("xmlresult").value = objXML.xml;
}

The first line calls the selectNodes() method, which you learned about throughout this chapter. The selectNodes() method requires one argument, which is the XPath expression (see Chapter 5) used to identify the artist. This expression says, Look in the catalog element for a cd element whose artist is equal to the artist entered by the user. The selectNodes() method returns a collection that contains information about all the CDs that are listed for the artist.

The second line examines the length property of the collection, which contains the total number of items returned by the selectNodes() method. If the length is zero, then the artist wasn’t found. An alert is displayed on the screen that the function returns without displaying any information.

Line three executes if the length is greater than zero, and assigns reference to the documentElement to the root variable.

Line four calls the selectNodes() method to retrieve information about all the CDs in the document.

Line five calls the removeAll() method, which removes all information about CDs from the XML document. The XML document now looks like this:

<?xml version="1.0"?>
<!DOCTYPE catalog SYSTEM "catalog.dtd"> <catalog></catalog>

Line six executes a for loop that calls the appendChild node to insert back into the XML document information about CDs from the selected artist. The XML document now looks like this:

<?xml version="1.0"?>
<!DOCTYPE catalog SYSTEM "catalog.dtd"> <catalog>
   <cd upc="602498678299">
      <artist>U2</artist>
      <title>How to Dismantle an Atomic Bomb</title>
      <price>13.98</price>

      <label>Interscope Records</label>
      <date>2004-11-23</date>  
   </cd>
</catalog>

The DisplayTitles() Function

You use the DisplayTitles() function to copy and display information contained in an XML document, but not alter the original document. Here’s the DisplayTitles() function:

function DisplayTitles()
{
   var result = "";
   var objNodes = objXML.selectNodes("/catalog/cd/title");
   for(var i=0; i < objNodes.length; i++)
   {
     
result += objNodes.item(i).text + "\r\n";
   }
   document.all("xmlresult").value = result;
}

You’ll notice that the DisplayTitles() function has many components that are found in previous examples shown in this chapter. And although we’re retrieving selected titles, you can use the same code to select any element from the XML document by simply replacing the element title with the appropriate element name.

The first line declares a variable. The pair of double quotations indicates an empty string is assigned to the variable to initialize it.

The second line calls the selectNodes() function to retrieve a collection that contains title elements.

The third line steps through the collection and assigns the text value of these elements to the result variable. Notice that it also assigns a \r\n. The \r is a carriage return and the \n is a new line. This simply places each element on its own line when the results are displayed.

The fourth line displays the text of the elements as shown here:

How to Dismantle an Atomic Bomb

Physical Graffiti

Rush in Rio

Songs in the Attic

Houses of the Holy

Are You Experienced?

The Times They Are A-Changin’

The DeleteNodes() Function

The DeleteNodes() function removes a specific node from the XML document. Here’s the DeleteNodes() function. You’ll notice that it requires one argument, which is the UPC code of the CD that is to be deleted from the XML document.

function DeleteNodes(upc)
{
   var objNodes = objXML.selectNodes(
       
"/catalog/cd[@upc='" + upc + "']"); 
   if(objNodes.length == 0)
   {
     
alert("Could not find node with upc " + upc);
     
return;
   }
   for(var i=0; i < objNodes.length; i++)
   {
     
objXML.documentElement.removeChild(objNodes.item(i));
   }
   document.all("xmlresult").value = objXML.xml;
}

The first line calls the selectNodes() method and passes it the XPath expression that’s used to locate elements whose upc attribute matches the CD UPC the user enters. The selectNodes() method returns a collection containing those elements.

The second line uses an if statement to evaluate if a CD matched the UPC. If not, then the length property is zero, the alert message is displayed, and the function returns without deleting any information from the XML document.

The third line executes only if there are elements to be deleted. It uses a for loop to step through the collection and calls the removeChild() method to remove the element.

The fourth line executes once the final element is deleted. This line displays the results we show here:

<?xml version="1.0"?>
<!DOCTYPE catalog SYSTEM "catalog.dtd"> <catalog>
  
<cd upc="602498678299">
      <artist>U2</artist>
      <title>How to Dismantle an Atomic Bomb</title>
      <price>13.98</price>
      <label>Interscope Records</label>
      <date>2004-11-23</date>
  
</cd>
  
<cd upc="75679244222">
      <artist>Led Zeppelin</artist>
      <title>Physical Graffiti</title>
      <price>22.99</price>
      <label>Atlantic</label>
      <date>1994-08-16</date>
   </cd>
  
<cd upc="74646938720">
      <artist>Billy Joel</artist>
      <title>Songs in the Attic</title>
      <price>10.99</price>
      <label>Sony</label>
      <date>1998-10-20</date>
   </cd>
  
<cd upc="75678263927">
      <artist>Led Zeppelin</artist>
      <title>Houses of the Holy</title>
      <price>10.98</price>
      <label>Atlantic</label>
     
<date>1994-07-19</date>
   </cd>
   <cd upc="8811160227">
      <artist>Jimi Hendrix</artist>
      <title>Are You Experienced?</title>
      <price>12.99</price>
      <label>Experience Hendrix</label>
      <date>1997-04-22</date>
  
</cd>
  
<cd upc="74640890529">
      <artist>Bob Dylan</artist>
      <title>The Times They Are A-Changin'</title>
      <price>9.99</price>
      <label>Sony</label>
      <date>1990-10-25</date>
   </cd>
</catalog>

The ValidateDocument() Function

You use the ValidateDocument() function to validate an XML document against the document’s DTD to determine if all elements in the XML document are defined in the DTD. Here’s the ValidateDocument() function. Notice that this is one of the simplest functions that you can build. It simply calls the validate() method and then evaluates the return value. If the returned errorCode is zero, then the XML document is valid. If the errorCode is other than zero, then the XML doesn’t comply with the DTD.

function ValidateDocument()
{
   var err = objXML.validate();
   if (err.errorCode == 0)
   {
     
alert("Document is valid.");
   }
   else
   {
      alert("Error validating document:" + err.reason);
   }
}

To test this function, return to the InsertFirst() function at the beginning of this chapter. Change the value of the new CD element in the text area of the HTML page to the following. Notice that the price element is deleted. This is required by the DTD.

<cd upc="75596280822"> 
   <artist>Phish</artist>
   <title>Live Phish, Vol. 15</title>
   <label>ELEKTRA/WEA</label>
   <date>2002-10-29</date>
</cd>

Click the InsertFirst() hyperlink and the XML document will look like this. Notice that price is missing, making the XML document invalid according to the DTD.

<?xml version="1.0"?>
<!DOCTYPE catalog SYSTEM "catalog.dtd"> <catalog>
  
<cd upc="75596280822">
      <artist>Phish</artist>
      <title>Live Phish, Vol. 15</title>
      <label>ELEKTRA/WEA</label>
      <date>2002-10-29</date>
   </cd>
  
<cd upc="602498678299">
      <artist>U2</artist>
      <title>How to Dismantle an Atomic Bomb</title>
      <price>13.98</price>
      <label>Interscope Records</label>
      <date>2004-11-23</date> 
   
</cd>
  
<cd upc="75679244222">
      <artist>Led Zeppelin</artist>
      <title>Physical Graffiti</title>
      <price>22.99</price>
      <label>Atlantic</label>
      <date>1994-08-16</date>
   </cd>
  
<cd upc="75678367229">
      <artist>Rush</artist>
      <title>Rush in Rio</title>
      <price>13.98</price>
      <label>Atlantic</label>
      <date>2003-10-21</date>
  
</cd>
  
<cd upc="74646938720">
      <artist>Billy Joel</artist>
      <title>Songs in the Attic</title>
      <price>10.99</price>
      <label>Sony</label>
      <date>1998-10-20</date>
  
</cd>
  
<cd upc="75678263927">
      <artist>Led Zeppelin</artist>
      <title>Houses of the Holy</title>
      <price>10.98</price>
      <label>Atlantic</label>
      <date>1994-07-19</date>
  
</cd>
  
<cd upc="8811160227">
      <artist>Jimi Hendrix</artist>
      <title>Are You Experienced?</title>
      <price>12.99</price>
      <label>Experience Hendrix</label>
      <date>1997-04-22</date>
  
</cd>
  
<cd upc="74640890529">
      <artist>Bob Dylan</artist>
      <title>The Times They Are A-Changin'</title>
      <price>9.99</price>
      <label>Sony</label>
      <date>1990-10-25</date>
  
</cd>
</catalog>

The DOMDocument object doesn’t automatically revalidate the XML document each time it’s altered, so no error message is displayed. Now select the Validate Document link on the HTML page. The ValidateDocument() function validates the XML document and displays an alert message indicating that the XML Document is invalid. The alert message is something like:

Error validating document: Element content is invalid according to the DTD/Schema. Expecting: price.

This is telling you that the price element was expected.

MSXML and XSLT

MSXML can be used to transform an XML document using XSLT (see Chapter 6). Many times you’ll want to transform an XML document to an HTML page so a browser can display it. We’ll show you how to do this with MSXML. Here’s the table row in the HTML page that contains the XSLT stylesheet:

<tr valign="top">
<td nowrap><a href="#" onclick="TransformDocument(document.all(
    'stylesheet').value); return false;">Transform Document:</a></td>
<td>
<textarea id="stylesheet" rows="20" cols="80">
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl=
    "http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/">
<html>
   <body>
   <h2>CD Listing</h2>
   <table border="1">
      <tr>
         <th align="center">UPC</th>
         <th align="center">Artist</th>
         <th align="center">Title</th>
      </tr>
      <xsl:for-each select="catalog/cd">
      tr> 
        <td>
           <xsl:value-of select="@upc"/>
        </td>
        <td>
           <xsl:value-of select="artist"/>  
        </td>
        <td>
           <xsl:value-of select="title"/> 
        </td>
      </tr>
     
</xsl:for-each>  
   </table>
   </body>
</html>
</xsl:template>
</xsl:stylesheet>
</textarea>
</td>
</tr>

The second table cell has a text area that contains the stylesheet. We’ve provided a default stylesheet, but you can change the default in the browser when you’re running this example. The first cell takes the stylesheet from the text area and passes it as an argument to the TransformDocument() function. Here’s the TransformDocument() function:

function TransformDocument(stylesheet)
{
   var xslProcessor;
   var xslTemplate = new ActiveXObject("Msxml2.XSLTemplate.4.0");
   var xslDocument = new ActiveXObject(
     "Msxml2.FreeThreadedDOMDocument.4.0"); 
   xslDocument.async = false; 
   xslDocument.loadXML(stylesheet);
   if (xslDocument.parseError.errorCode != 0)
   {
      var myErr = xmlDoc.parseError;
      alert("You have error " + myErr.reason);
      return;
   }
   xslTemplate.stylesheet = xslDocument; 
   xslProcessor = 
   xslTemplate.createProcessor();
   xslProcessor.input = objXML;
   xslProcessor.transform();
   window.frames.htmlresult.document.open();
   window.frames.htmlresult.document.clear();
   window.frames.htmlresult.document.write(xslProcessor.output); 
   window.frames.htmlresult.close();
}

The first line declares a variable.

The second line creates an XSLTemplate object and assigns it to a variable.

The third line creates a DOMDocument object and assigns it to a variable.

The fourth line sets the async property to false so the next statement doesn’t execute until the document is loaded.

The fifth line calls the loadXML() method and passes it the stylesheet.

The sixth line determines if there is an error. If so, then an error message is displayed and the function returns to the statement that called it without transforming the XML document.

The seventh line executes if there isn’t an error. This line assigns the xslDocument to the stylesheet property of the xslTemplate.

The eighth line calls the createProcessor() method to create an xslProcessor.

The ninth line assigns the XML document to the input property of the xslProcessor.

The tenth line calls the transform() method to transform the XML document.

Lines 11 through 14 write the transformed XML document to the browser. The results are shown next.

CD Listing

Here is the list of CDs organized by UPC, artist, and title that is produced by using MXSML to transform an XML document using XSLT. This is illustrated in the previous section of this chapter.

UPC

Artist

Title

602498678299

U2

How to Dismantle an Atomic Bomb

75679244222

Led Zeppelin

Physical Graffiti

75678367229

Rush

Rush in Rio

74646938720

Billy Joel

Songs in the Attic

75678263927

Led Zeppelin

Houses of the Holy

8811160227

Jimi Hendrix

Are You Experienced?

74640890529

Bob Dylan

The Times They Are A-Changin’

Summary

In this chapter you learned how to combine the power of XML and the MSXML application program interface that enables you to interact with an XML document from within an application written in one of the popular programming languages.

MSXML enables you to access an XML document by using an application that you create rather than accessing the XML document using a browser. MSXML contains preprogrammed classes and functions that contain code necessary to access and manipulate information in an XML document.

You need to call the appropriate classes and functions from within your application to interact with an XML document without having to write tedious code to read and parse the XML document. MSXML works with C, C++, Visual Basic, VBScript, Jscript, and JavaScript.

Quiz

  1. MSXML can only be used with JavaScript.

    a. True

    b. False 
  2. The async = false means

    a. Statements will continue to execute as the XML document is being loaded.

    b. Statements will not execute until the XML document is being loaded.

    c. The XML document is synchronized to the HTML page.

    d. None of the above. 
  3. firstChild is a

    a. Property containing a reference to the first child of an element

    b. Method that makes the current node the first child

    c. Method that substitutes the first node for the last node

    d. Method that substitutes the last node for the first node 
  4. createElement(“title”) means

    a. Create a new HTML element

    b. Create a new XML element

    c. Create a title for a new HTML element

    d. Create an attribute called title for the current XML element 
  5. “/catalog/cd[@upc=‘“ + upc + “‘] means

    a. Find the text that matches the value of the upc variable in the cd element

    b. Find the upc attribute that matches the value of the upc variable in the cd element

    c. Find the upc element that matches the UPC in the cd element

    d. All of the above 
  6. An XML document can be validated against a DTD by calling the validate() method.

    a. True

    b. False
  7. The appendChild() appends a node to the end of an XML document.

    a. True

    b. False 
  8. The version is specified in ActiveXObject(“MSXML2 .DOMDocument.4.0”) because

    a. Versions are designed to coexist with previous versions.

    b. Only the version specified can be used with the XML document.

    c. It identifies potential conflicts in versions.

    d. None of the above.
  9. The loadXML() method is used when the document is passed as a string.

    a. True

    b. False 
  10. getAttribute(“upc”) retrieves the value of the upc attribute.

    a. True
    b. False
blog comments powered by Disqus
XML ARTICLES

- More on Triggers and Styles and Control Temp...
- Looking at Triggers with Styles and Control ...
- A Closer Look at Styles and Control Templates
- Styles and Control Templates
- Properties and More in XAML
- Elements and Attributes in XAML
- XAML in a Nutshell
- Importing XML Files into Access 2007
- Using MSXML3.0 with VB 6.0
- MSXML, concluded
- MSXML, continued
- MSXML Tutorial
- Generating XML Schema Dynamically Using VB.N...
- XSL Transformations using ASP.NET
- Applying XSLT to XML Using ASP.NET

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 9 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials