Jump to content

Problems parsing XML Feed in Javascript


Recommended Posts

I'm just learning how to parse an XML feed with JavaScript, but I'm having some problems. If I copy and paste the code from the XML feed into an internal file, and I reference that file in my code, it works fine. But when I try to change the XML source doc to the XML feed's URL (http://codeamber.org/a1xl04act/amberalert.xml), nothing shows up. Obviously there's something that I'm missing when it comes to parsing an internal XML doc vs. an XML feed. In addition to pulling in the main elements, I'm trying to pull the attributes of some elements without success. So if anyone could let me know what I'm missing and/or doing wrong, it would be greatly appreciated. I've included my code below:

<%@LANGUAGE="JAVASCRIPT" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><title>Pull XML  Feed</title><script type="text/javascript">var xmlDoc;function loadXML(){//load xml file// code for IEif (window.ActiveXObject){	xmlDoc=new ActiveXObject("Microsoft.XMLDOM");	xmlDoc.async=false;	xmlDoc.load("pullxmlfeed.xml");//I want this to pull from external XML feed at http://codeamber.org/a1xl04act/amberalert.xml	getmessage();}// code for Mozilla, Firefox, Opera, etc.else if (document.implementation && document.implementation.createDocument){	xmlDoc=document.implementation.createDocument("","",null);	xmlDoc.load("pullxmlfeed.xml");//I want this to pull from external XML feed at http://codeamber.org/a1xl04act/amberalert.xml	xmlDoc.onload=getmessage;}else{	alert('Your browser cannot handle this script');}}function getmessage(){document.getElementById("Alertstatus").innerHTML=xmlDoc.getElementsByTagName("Alertstatus")[0].childNodes[0].nodeValue;document.getElementById("FullText").innerHTML=xmlDoc.getElementsByTagName("FullText")[0].childNodes[0].nodeValue;document.getElementById("Alertinfo").innerHTML=xmlDoc.getElementsByTagName("Alertinfo")[0].childNodes[0].nodeValue;document.getElementById("AlertState").innerHTML=Alertinfo.getElementsByTagName("states")[0].childNodes[0].nodeValue;//I want to pull attribute 'status' from 'Alertinfo' nodedocument.getElementById("Victim").innerHTML=xmlDoc.getElementsByTagName("Victim")[0].childNodes[0].nodeValue;}</script></head><body onload="loadXML()"><h1>Pull XML Feed</h1><p><b>Alertstatus:</b> <span id="Alertstatus"></span><br /><b>FullText:</b> <span id="FullText"></span><br /><b>Alertinfo:</b> <span id="Alertinfo"></span><br /><b>AlertState:</b> <span id="AlertState"></span><br /><b>Victim:</b> <span id="Victim"></span></p></body></html>

Link to post
Share on other sites

There are a few things here worth considering1. I noticed <%@ LANGUAGE="JAVASCRIPT @> in your first line. This tells me you are using an ASP page, but then you push the parsing to the client. Why not let the server do the work? You're going to have all kinds of problems with rendering XML at the client, not the least being security and permission to download parsers, etc...2. Microsoft.XMLDOM parser has been deprecated for several years. That was version 0.5. It was only able to do 1/2 the ability of the spec. It lacked support for XSLT processing (it uses XSL). You should upgrade to version 6.03. I was able to get this too run in my IE 7.0 as an HTML page. So there is no problem with loading the remote XML. xmlDoc=new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async=false; alert(xmlDoc.load("http://codeamber.org/a1xl04act/amberalert.xml")) alert(xmlDoc.xml)4. Try rewriting as an ASP page, its not that hard. No need to check for browser type as the server will be doing the work. Hope that this helps a little. Following code works just fine for me using IIS 5.0 and IE 7.0

<%@ LANGUAGE="JAVASCRIPT" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head>	<title>Pull XML  Feed</title></head><%	var xmlDoc;	xmlDoc = new ActiveXObject("Microsoft.XMLDOM") <!-- this will still work -->//	xmlDoc = new ActiveXObject("Msxml2.DOMDocument.4.0") <!-- you should use this -->   	xmlDoc.async=false;	xmlDoc.setProperty("ServerHTTPRequest", true) <!-- You need this for both to get a remote XML feed this way -->	if (xmlDoc.load("http://codeamber.org/a1xl04act/amberalert.xml") == false)	{		Response.Write("Failed to load xml");	}%><body>	<h1>Pull XML Feed</h1>	<p><b>Alertstatus:</b> <span id="Alertstatus"><%=xmlDoc.selectSingleNode("//Alertstatus").text %></span><br />	<b>FullText:</b> <span id="FullText"><%=xmlDoc.selectSingleNode("//FullText").text %></span><br />	<b>Alertinfo:</b> <span id="Alertinfo"></span><br />	<b>AlertState:</b> <span id="AlertState"><%=xmlDoc.selectSingleNode("//Alertinfo/@states").text %></span><br />	<b>Victim:</b> <span id="Victim"><%=xmlDoc.selectSingleNode("//Victim/@name").text %></span>	</p></body></html>

Link to post
Share on other sites

Ok, that makes perfect sense. I have some knowledge in everything, but I'll perpetually be a newbie I think.Anyway, I copied and pasted your code into my editor and gave it a look. It came across great in IE6, IE7 and FF, but I received the following error message when I tried to replace 'xmlDoc = new ActiveXObject("Microsoft.XMLDOM")' with 'xmlDoc = new ActiveXObject("Msxml2.DOMDocument.4.0")' per your suggestion:Microsoft JScript runtime error '800a01ad'Automation server can't create object/pullxmlfeed.asp, line 14 So I changed 'new ActiveXObject("Msxml2.DOMDocument.4.0")' to 'new ActiveXObject(MSXML2.DOMDocument.3.0")', and it worked great in all 3 browsers (YEAH). Thanks for your help...I REALLY appreciate it. Thank GOD for this forum:)

Link to post
Share on other sites
Glad to help. The reason for the error on the parser is that you would need to download it from Microsoft first. Sorry about that. The XMLDOM is inherent and still works. But you should take the time and get the latest when you have a chance.
Will do. Thanks again!P.S. For any users that view this thread in the future, here is a download of the XML parser (MSXML 4.0 Service Pack 2) mentioned by aalbetski: http://www.microsoft.com/downloads/details...;displaylang=en
Link to post
Share on other sites
  • 1 month later...

Well, this is gone in a different direction thanks to aalbetski's help, and now I have another question:The code in this thread works great at pulling nodes from an external XML feed. I have an internal client-side "news scroller" script (JavaScript) that I want to display some of the nodes from the server-side code.So can I pull XML nodes from an external XML feed, declare variables from that code, and then use those server-side variables within client-side code?Something like this:

<%@ LANGUAGE="JAVASCRIPT" %><%	var xmlDoc;	xmlDoc = new ActiveXObject("Msxml2.DOMDocument.3.0")	xmlDoc.async=false;	xmlDoc.setProperty("ServerHTTPRequest", true) <!-- You need this for both to get a remote XML feed this way -->	if (xmlDoc.load("http://codeamber.org/a1xl04act/amberalert.xml") == false)	{		Response.Write("Failed to load xml");	}var amberDescription = xmlDoc.selectSingleNode("//FullText").text;//<<----CAN I PULL THIS INTO CLIENT-SIDE CODE???%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head>	<title>Pull XML  Feed</title><script type="text/javascript" language="javascript">var pausecontent=new Array()//These need to be dynamically pulled from existing XML feeds:pausecontent[0]='<strong><a href="amberalert.aspx">Amber Alert:</a></strong> ' + amberDescription + ' <a href="amberdetails.aspx">Learn more >></a>'pausecontent[1]='<strong><a href="anotherfeed.aspx">Another Feed:</a></strong> ' + anotherfeedDescription + ' <a href="anotherfeed.aspx">Learn more >></a>'//.....MORE JS CODE GOES HERE TO CREATE THE ACTUAL SCROLLER...}</script></head><body>	<h1>Pull XML Feed</h1>	<p><b>Alertstatus:</b> <span id="Alertstatus"><%=xmlDoc.selectSingleNode("//Alertstatus").text %></span><br />	<b>FullText:</b> <span id="FullText"><%=xmlDoc.selectSingleNode("//FullText").text %></span><br />	<b>Alertinfo:</b> <span id="Alertinfo"></span><br />	<b>AlertState:</b> <span id="AlertState"><%=xmlDoc.selectSingleNode("//Alertinfo/@states").text %></span><br />	<b>Victim:</b> <span id="Victim"><%=xmlDoc.selectSingleNode("//Victim/@name").text %></span>	</p>	<script type="text/javascript">		new pausescroller(pausecontent, "scroller", "someclass", 8000)	</script></body></html>

I don't know much about using client-side code in conjunction with server-side code, so if anyone can let me know if this is possible, that would be great. Thanks.

Link to post
Share on other sites
So can I pull XML nodes from an external XML feed, declare variables from that code, and then use those server-side variables within client-side code?
No, there is no relation between client-side code and server-side code. They don't use any of the same namespaces, scoping, memory addressing, and they don't even run on the same computer or at the same time. The memory that contains all of the server-side data is memory that is installed in the web server, the client computer doesn't have access to the web server's memory space. The server-side code will need to print a variable structure for the client-side code to use. If you have a string variable server-side that you want to be available for the client-side code you would do this:<script type="text/javascript">var val = "<%=val%>";</script>
Link to post
Share on other sites
No, there is no relation between client-side code and server-side code. They don't use any of the same namespaces, scoping, memory addressing, and they don't even run on the same computer or at the same time. The memory that contains all of the server-side data is memory that is installed in the web server, the client computer doesn't have access to the web server's memory space. The server-side code will need to print a variable structure for the client-side code to use. If you have a string variable server-side that you want to be available for the client-side code you would do this:<script type="text/javascript">var val = "<%=val%>";</script>
That's what I thought, but I didn't think it would hurt to ask.I did your suggestion, like this:<script type="text/javascript"> var strAlertStatus = <%=(strYada)%> document.write("strAlertStatus: " + strAlertStatus); </script>When I view it in the browser, nothing is displayed. But when I view the source code, this is the result:<script type="text/javascript"> var strAlertStatus = The State of New Mexico canceled the Amber Alert after the child was found safe on Sunday afternoon. The suspect remains at large at this time. document.write("strAlertStatus: " + strAlertStatus); </script>So I'm not sure if the variable would be usable in the client-side JS, but if I add double-quotes around the variable's value, it might work. Is there an easy way to add those double-quotes to this variable's value? I thought it was <%=(""" + strYada + """)%>, but that just resulted in: var strAlertStatus = """ + The State of..." in the source code. Any ideas would be great. Thanks.
Link to post
Share on other sites
It worked great! Thanks for your help justsomeguy....I really appreciate it. This forum rocks.
Now I've run into another issue, and hopefully you or someone can help:I want to display the scroller only if the "//Alertstatus/@status" node = "open", and the "//Alertinfo/@states" node = "CO". So first, I created a copy of the XML feed on another domain to test this out (xmlfeedcopy.xml). Next, I'm trying to create a JavaScript loop for the external XML feed, but I'm only getting the first element's values. Here's what I have so far:XML Doc (sample copy of external feed - not real data):
<?xml version="1.0" encoding="ISO-8859-1"?><AmberAlerts>	<AmberAlert issued="11/05/07" updated="11/06/07 7:45 AM" sourceurl="http://codeamber.org/mendozamn/" issued_gmt="11/06/07" updated_gmt="11/06/07 13:45 GMT">		<Alertstatus status="closed">			The Minnesota Crime Alert Network and the St. Paul Police Department canceled the  Amber Alert Tuesday morning after the girl was found safe and a suspect taken into custody.		</Alertstatus>		<FullText>			The Minnesota Crime Alert Network and the St. Paul Police Department canceled the  Amber Alert Tuesday morning after the girl was found safe and a suspect taken into custody. The Minnesota Crime Alert Network and the St. Paul Police Department had issued the  Amber Alert Monday evening after the girl was assaulted and forced into the suspect vehicle. Jacqueline Mendoza, 15, a 5-foot tall Hispanic female,  110 pounds, brown eyes, long black hair and a scar below her left eye. She was wearing last seen wearing a brown sweater, yellow Capri pants and black tennis shoes. The suspects are David Guzman, an 18 year old Hispanic male, 5'10 with black hair and brown eyes weighing 180 pounds. He wqs last seen wearing a dark blue nylon "Los Angeles" jacket with white lettering, checkered light blue shirt. Police say the suspect has a history of handguns and long guns. A second suspect is an unknown Hispanic female approximately 30 years old, 5' 11", brown eyes and black hair with a heavy build.. She was last seen wearing gray sweat pants and black "Los Angeles" jacket with white lettering. The suspect vehicle is a 1990's light blue 4-door Chevy with Minnesota tag  MTH 303 or 303 MTH. Anyone with information is asked to call Jim Gray at the Bureau of Criminal Apprehension at 651-266-3659 or 651-291-1111 or dial 911.		</FullText>			<Alertinfo date="Monday November 5" location="St. Paul MN US" zip="551" fullzip="55101" states="MN" Addstates="" counties="" date_gmt="Tuesday November 6">		</Alertinfo>		<Victims>				<Victim race="Hispanic" gender="female" age="15 yrs." height="5'" weight="110"  hair="black" eyes="brown" name="Jacqueline Mendoza">				She was wearing last seen wearing a brown sweater, yellow Capri pants and black tennis shoes.				<Picture>"</Picture>				<Picturelarge orientation=""></Picturelarge>				</Victim>		</Victims>	</AmberAlert>	<!-- ***THIS IS THE ONE THAT I WANT PULLED*** -->	<AmberAlert issued="12/19/07" updated="12/19/07 7:45 AM" sourceurl="http://codeamber.org/kwilliams/" issued_gmt="12/19/07" updated_gmt="12/19/07 13:45 GMT">		<Alertstatus status="open">			The Colorado Crime Alert Network and the Elizabeth Police Department have issued an amber alert for...		</Alertstatus>		<FullText>			The Colorado Crime Alert Network and the Elizabeth Police Department have issued an amber alert for...		</FullText>			<Alertinfo date="Wednesday December 19" location="Elizabeth CO US" zip="801" fullzip="80107" states="CO" Addstates="" counties="" date_gmt="Wednesday December 19">		</Alertinfo>		<Victims>				<Victim race="Black" gender="female" age="32 yrs." height="5'1" weight="115"  hair="brown" eyes="brown" name="K. Williams">				She was wearing last seen wearing a black sweater, gray pants and black boots.				<Picture>"</Picture>				<Picturelarge orientation=""></Picturelarge>				</Victim>		</Victims>	</AmberAlert></AmberAlerts>

ASP Doc (JavaScript):

<%@ LANGUAGE="JAVASCRIPT" %><%	var xmlDoc;	xmlDoc = new ActiveXObject("Msxml2.DOMDocument.3.0")	xmlDoc.async=false;	xmlDoc.setProperty("ServerHTTPRequest", true)		//Load check	//if (xmlDoc.load("http://codeamber.org/a1xl04act/amberalert.xml") == false) {//then LIVE VERSION	if (xmlDoc.load("http://www.anotherdomain.com/docs/xml/xmlfeedcopy.xml") == false) {//then TEST VERSION 		Response.Write("Failed to load xml");	} //end if		//***LOOP NEEDS TO GO HERE***	//***THIS IS WHAT I HAVE THAT'S ONLY PULLING THE FIRST XML ELEMENT	var x = xmlDoc.getElementsByTagName("AmberAlert");	for (i=0;i<x.length;i++) {		//Declare variables		var strAlertStatus_node = xmlDoc.selectSingleNode("//Alertstatus/@status").text;		var strAlertState_node = xmlDoc.selectSingleNode("//Alertinfo/@states").text;	}//end loop	//THIS IS ANOTHER POSSIBLE OPTION, BUT I'M NOT SURE HOW TO USE IT PROPERLY WITH AN XML DOCUMENT	//var x = xmlDoc.getElementsByTagName("AmberAlert");	//var myArray = new Array(x);	//for (i=0;i<myArray.length;i++) {//begin loop		//Response.Write(myArray[i]);	//}//end loop		if (strAlertStatus_node == "open" && strAlertState_node == "CO") {//then		var objScrollerStatus = true	}//end if	if (objScrollerStatus == true) {//then		//Display results of loop		Response.Write("strAlertStatus_node: " + strAlertStatus_node + "<br />");		Response.Write("strAlertState_node: " + strAlertState_node + "<br />");		Response.Write("objScrollerStatus: " + objScrollerStatus + "<br />");	}//end if%>

WANTED HTML OUTPUT:strAlertStatus_node: openstrAlertState_node: COobjScrollerStatus: trueI know that I'm a bit lost, but I can't find much documentation on how to accomplish this. Any and all help would be appreciated. Thanks.

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...