MSXML Tutorial - Getting Down and Dirty with MSXML
(Page 2 of 5 )
Let’s jump in. To start learning MSXML, you’ll first create an XML document. The XML document is a catalog of CDs that we’ll simply call catalog.xml. It contains seven CDs, as you’ll see in the code that follows. Enter this XML code into a file and save it to your drive. Be sure to call the file catalog.xml.
<?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="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>
You’ll notice that the XML document refers to the catalog.dtd. As you’ll recall from Chapter 3, a DTD file contains the document type definition that defines the markup tags that can be used in the XML document and specifies the parent-child structure of those tags. The XML parser references the DTD when parsing elements of the XML document.
Create a DTD for this example. You do this by writing the following information into a file and saving the file as catalog.dtd in the directory that contains the catalog .xml file.
<!ELEMENT catalog (cd*)>
<!ELEMENT cd (artist, title, price, label, date)>
<!ELEMENT artist (#PCDATA)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT price (#PCDATA)>
<!ELEMENT label (#PCDATA)>
<!ELEMENT date (#PCDATA)>
<!ATTLIST cd
upc CDATA #REQUIRED>
The final step you’ll take to prepare to learn MSXML is to create the HTML file that contains the JavaScript used to access the catalog.xml document. The HTML file follows. Some of it is familiar because it’s HTML. Other parts, you’ll understand if you know JavaScript (don’t worry if you don’t understand them; we explain JavaScript throughout this chapter). However, the portions of the HTML file that use MSXML are probably confusing, even if you previously worked with JavaScript.
For now, simply create this HTML file and save it to a file called default.html in the directory where you saved catalog.xml and catalog.dtd. We explain each part of the HTML file throughout this chapter.
<html>
<head>
<script language="javascript">
var objXML;
function LoadDocument()
{
var inputfile = document.all("inputfile").value;
objXML = new ActiveXObject("MSXML2.DOMDocument.4.0");
objXML.async = false;
objXML.load(inputfile);
if (objXML.parseError.errorCode != 0)
{
alert("Error loading input file: " + objXML.parseError.reason);
return;
}
document.all("xmldoc").value = objXML.xml;
}
function InsertFirst()
{
var objNewNode = LoadNewNode();
if(objNewNode == null)
{
return;
}
var root = objXML.documentElement;
root.insertBefore(objNewNode,
root.firstchild);
document.all("xmlresult").value = objXML.xml;
}
function InsertLast()
{
var objNewNode = LoadNewNode();
if(objNewNode == null)
{
return;
}
var root = objXML.documentElement;
root.appendChild(objNewNode);
document.all("xmlresult").value = objXML.xml;
}
function InsertBefore(upc)
{
var objNewNode = LoadNewNode();
if(objNewNode == null)
{
return;
}
var root = objXML.documentElement;
var objNodes = objXML.selectNodes("/catalog/cd[@upc='" + upc + "']");
if(objNodes.length == 0)
{
alert("Could not find node with upc " + upc);
return;
}
root.insertBefore(objNewNode, objNodes.item(0));
document.all("xmlresult").value = objXML.xml;
}
function InsertAfter(upc)
{
var objNewNode = LoadNewNode();
if(objNewNode == null)
{
return;
}
var root = objXML.documentElement;
var childNodes = root.childNodes;
for(var i=0; i < childNodes.length; i++)
{
var node = childNodes.item(i);
var nodeUPC = node.getAttribute("upc");
if(nodeUPC == upc)
{
root.insertBefore(objNewNode, childNodes.item(i+1));
document.all("xmlresult").value = objXML.xml;
return;
}
}
alert("Could not find node with upc " + upc);
}
function LoadNewNode()
{
var xmlNewNode = document.all("newnode").value;
var objNewNode = new ActiveXObject("MSXML2.DOMDocument.4.0");
objNewNode.async = false;
objNewNode.loadXML(xmlNewNode);
if (objNewNode.parseError.errorCode != 0)
{
alert("Error loading new node: " + objNewNode.parseError.reason);
return null;
}
else
{
return objNewNode.documentElement;
}
}
function CreateAndAppendNode()
{
var upc = document.all("createUpc").value;
var artist = document.all("createArtist").value;
var title = document.all("createTitle").value;
var price = document.all("createPrice").value;
var label = document.all("createLabel").value;
var date = document.all("createDate").value;
var elementCd = objXML.createElement("cd");
elementCd.setAttribute("upc", upc);
var elementArtist = objXML.createElement("artist");
var textArtist = objXML.createTextNode(artist);
elementArtist.appendChild(textArtist);
elementCd.appendChild(elementArtist);
var elementTitle = objXML.createElement("title");
var textTitle = objXML.createTextNode(title);
elementTitle.appendChild(textTitle); elementCd.appendChild(elementTitle);
var elementPrice = objXML.createElement("price");
var textPrice = objXML.createTextNode(price);
elementPrice.appendChild(textPrice);
elementCd.appendChild(elementPrice);
var elementLabel = objXML.createElement("label");
var textLabel = objXML.createTextNode(label);
elementLabel.appendChild(textLabel);
elementCd.appendChild(elementLabel);
var elementDate = objXML.createElement("date");
var textDate = objXML.createTextNode(date);
elementDate.appendChild(textDate);
elementCd.appendChild(elementDate);
var root = objXML.documentElement;
root.appendChild(elementCd);
document.all("xmlresult").value = objXML.xml;
}
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;
}
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;
}
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;
}
function ValidateDocument()
{
var err = objXML.validate();
if (err.errorCode == 0)
{
alert("Document is valid.");
}
else
{
alert("Error validating document:" + err.reason);
}
}
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();
}
</script>
</head>
<body onload="LoadDocument();">
<table cellpadding="5" class=contentpaneopen>
<tr>
<td nowrap>File name: <input type="text"
id="inputfile" value="catalog.xml"></td>
<td><input type="button" onclick="LoadDocument();"
value="Load Document"></td>
</tr>
<tr valign="top">
<td>XML Document:</td>
<td><textarea id="xmldoc" rows="20" cols="80" readonly>
</textarea></td>
</tr>
<tr valign="top">
<td nowrap>
<a href="#" onclick="InsertFirst(); return false;">
Insert First:</a><br>
<a href="#" onclick="InsertLast(); return false;">
Insert Last:</a><br>
<a href="#" onclick="InsertBefore(
document.all('upcBefore').value);
return false;">Insert Before UPC:</a>
<input type="text" id="upcBefore"
value="75678367229" size="15"><br>
<a href="#" onclick=
"InsertAfter(document.all('upcAfter').value);
return false;">Insert After UPC:</a>
<input type="text" id="upcAfter"
value="75678367229" size="15"><br>
</td>
<td><textarea id="newnode" rows="10" cols="80">
<cd upc="75596280822">
<artist>Phish</artist>
<title>Live Phish, Vol. 15</title>
<price>26.99</price>
<label>ELEKTRA/WEA</label>
<date>2002-10-29</date>
</cd>
</textarea>
</td>
</tr>
<tr valign="top">
<td nowrap><a href="#" onclick="CreateAndAppendNode();
return false">Create/Append Node</a></td>
<td nowrap>
upc: <input type="text" id="createUpc"
value="75596280822" size="15"><br>
artist: <input type="text" id="createArtist"
value="Phish" size="15"><br>
title: <input type="text" id= "createTitle"
value="Live Phish, Vol. 15" size="15"><br>
price: <input type="text" id="createPrice"
value="26.99" size="15"><br>
label: <input type="text" id="createLabel"
value="ELEKTRA/WEA" size="15"><br>
date: <input type="text" id="createDate"
value="2002-10-29" size="15">
</td>
</tr>
<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>
<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>
<tr valign="top">
<td>XML Result:</td>
<td><textarea id="xmlresult" rows="20" cols="80"></textarea></td>
</tr>
<tr valign="top">
<td>HTML Result:</td>
<td><iframe id="htmlresult"
src="about:blank" width="100%" height="300"></td>
</tr>
</table>
</body>
</html>
Next: Loading a Document >>
More XML Articles
More By McGraw-Hill/Osborne
|
This article is excerpted from chapter 10 of XML DeMYSTified, written by Jim Keogh and Ken Davidson (McGraw-Hill/Osborne, 2005; ISBN: 0072262109). Check it out today at your favorite bookstore. Buy this book now.
|
|