Howard Johnson
Howard Johnson

Reputation: 1

Need help parsing xml with javascript

First let me thank you for the assistance, I am new to Javascript, and want to learn to parse a >.xml file into my javascript. The file I want to parse is contact.xml, located in my root folder. Again, thank you.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1     /DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function loadXMLDoc(XMLname)
{
var xmlDoc;
if (window.XMLHttpRequest)
{
xmlDoc=new window.XMLHttpRequest();
xmlDoc.open("GET",XMLname,false);
xmlDoc.send("");
return xmlDoc.responseXML;
}
// IE 5 and IE 6
else if (ActiveXObject("Microsoft.XMLDOM"))
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load(XMLname);
return xmlDoc;
}
alert("Error loading document!");
return null;
}
<title>Contacts</title>
</script>
</head>

<body>
<script type="text/javascript">
xmlDoc = loadXMLDoc("contactinfo.xml") // Path to the XML file;
var M = xmlDoc.getElementsByTagName("item");
for (i=0;i<M.length;i++){
document.write("<div style='width:450px;'>")
document.write("<h2>"+xmlDoc.getElementsByTagName("item")[i].childNodes[0].nodeValue+"</h2>");
document.write("<p>" + xmlDoc.getElementsByTagName("servicephone")[i].childNodes[0].nodeValue+    "</p>");
document.write("<p><a href='" + xmlDoc.getElementsByTagName("email")[i].childNodes[0].nodeValue   +"</p>);
document.write("</div>")
}
</script>

</body>
</html>


*Here is my .xml file*

<?xml version="1.0" encoding="utf-8" ?>
<Contacts>
<item servicephone="(800) 500-0066" 
email="[email protected]" 
url="http://www.fsig.com" 
address="5000 Barcilona Beach Rd. Wilmington, NC 28000">
</item>
</Contacts>

Upvotes: 0

Views: 493

Answers (1)

James Black
James Black

Reputation: 41848

You need to go down the hierarchy, so, first find the Contacts node, then inside there you can get all the tagnames as you have.

You have a great deal of attributes so you may find this useful also:

node.attributes["url"].nodeValue

So just loop through all the items, then I would just copy itemelem[t] to node just to make it easier, then you get the attributes you need.

Depending on the browser you are using most of them come with some javascript debugger, so you can put in breakpoints and look at the values in the variables and see what the next step needs to be.

Upvotes: 1

Related Questions