Click to See Complete Forum and Search --> : How to read an XML file with JavaScript
mervinoh
04-09-2003, 04:02 PM
I have a XML file that contains links - names and URLs.
I am trying to read the XML data into an array in JavaScript.
I have found some examples using ActiveXObject.
Do all the browser support ActiveXObject?
Is there another way to read the XML data, without using ActiveXObject?
Thanks for your help.
I believe so. Javascript, I know for a fact, can read and implement XML into HTML tables. Here is some code for that( (I don't know if it will work in Netscape) :
<html>
<head>
<title>XML example</title>
<!-- IE-specific tag to import XML document -->
<xml id="fXML" src="stitch.xml"></xml>
<script language="JavaScript">
function getOrder()
{
itemTypesOrdered = ""
// IE-specific tags to bring in XML document
rootXML = document.all("fXML").XMLDocument
orderXML = rootXML.documentElement
numDiffItems = orderXML.childNodes.length
if (numDiffItems)
{
document.write("<table border=1 cellpadding=5>")
document.write("<tr><td><b>Item</b></td><td><b>Quantity</b></td>")
document.write("<td><b>Color</b></td><td><b>Size</b></td></tr>")
for (i=0; i<numDiffItems; i++)
{
hasItems = orderXML.childNodes[i].childNodes.length
if (hasItems)
{
itemType = orderXML.childNodes[i]
for (j=0; j<hasItems; j++)
{
singleItem = itemType.childNodes[j]
itemName = singleItem.nodeName
quantity = singleItem.getAttribute("quantity")
// see if size and color are subelements
if (singleItem.childNodes.length)
{
// loop over child nodes get color, size
for (k=0; k<singleItem.childNodes.length; k++)
{
subName = singleItem.childNodes[k].nodeName
if (subName == "size")
{
size = singleItem.childNodes[k].
firstChild.nodeValue
}
else if (subName == "color")
{
itemColor = singleItem.childNodes[k].
firstChild.nodeValue
}
}
}
else
{
itemColor = singleItem.getAttribute("color")
size = "n/a"
}
document.write("<tr>")
document.write("<td>" + itemName + "</td>")
document.write("<td>" + quantity + "</td>")
document.write("<td>" + itemColor + "</td>")
document.write("<td>" + size + "</td>")
document.write("</tr>")
}
}
else
{
// create lines for mugs and martini glasses, which
// only use quantity
itemName = orderXML.childNodes[i].nodeName
quantity = orderXML.childNodes[i].getAttribute("quantity")
document.write("<tr>")
document.write("<td>" + itemName + "</td>")
document.write("<td>" + quantity + "</td>")
document.write("</tr>")
}
}
}
document.write("</table>")
}
</script>
</head>
<body onLoad="getOrder()">
</body>
</html>
There are also some good examples at www.dynamicdrive.com
khalidali63
04-09-2003, 07:30 PM
ActiveXObjects are only supported in IE browsers.To make your solution Browser independent use xsl/xslt to format ur xml
Khalid
mervinoh
04-10-2003, 01:08 AM
I am not looking to format the XML file. I only want to use the data, like a config file.
Yes I want it to be browser and platform independent.