XML Parsing in Javascript
I'm trying to parse an xml coming from an XMLHttpRequest (for a Firefox extension). In the following code, req is an XMLHttpRequest object. I did req.overrideMimeType("text/xml");
after declaring req.
var shortURL;
var xmlDoc = document.implementation.createDocument("","",null);
xmlDoc.async = false;
xmlDoc = req.responseXml;
if (xmlDoc.readyState == 4){
shortURL = xmlDoc.documentElement.childNodes[8].text;
}
If I use req.responseXml
I get an error saying "xmlDoc is not declared" for the line after xmlDoc = req.responseXml;
If I use req.responseText
, xmlDoc.readyState == 4
turns false.
I don't do much of javascript so please tel开发者_开发百科l me if I'm doing something wrong here.
I generally prefer using responseText
and then parsing the XML using the browser's built in XML parsing library. After that, I generally convert the resulting XML document tree, or a sub tree, to JSON for easy access in JavaScript.
I wrote a tiny utility library for this here:
http://earth-api-samples.googlecode.com/svn/trunk/demos/myearth/lib/xmlutil.js
The usage is pretty simple:
var json = xmlNodeToJson(parseXml(req.responseText);
Hai chanux,
May this will help you to know basics of xml parser
http://www.hiteshagrawal.com/javascript/javascript-parsing-xml-in-javascript
AJAX responseXML errors
or try changing
shortURL = xmlDoc.documentElement.childNodes[8].Text;
to
shortURL = xmlDoc.documentElement.childNodes[8].firstChild.nodeValue;
or use this function and change it for yours...
function parseXML()
{
if (xmlDoc.readyState == 4 && xmlDoc.status == 200)
{
xmlDoc = xmlDoc.responseXML;
regions = xmlDoc.getElementsByTagName("region");
for (var i = 0; i < regions.length; i++)
{
if (regions[i].getAttribute("id") == regID)
{
var browserName = navigator.userAgent;
var isIE = browserName.match(/MSIE/);
if (isIE)
{
var hotelprice = regions[i].childNodes[0].firstChild.nodeValue;
var pkgprice = regions[i].childNodes[1].firstChild.nodeValue;
}
else
{
var hotelprice = regions[i].childNodes[1].textContent;
var pkgprice = regions[i].childNodes[3].textContent;
}
document.getElementById("hotel").innerHTML = "$"+hotelprice;
document.getElementById("package").innerHTML = "$"+pkgprice;
}
}
}
}
Do you need to use the DOM? If not, use E4X. It's as simple as
shortURL = new XML(req.responseText).child(8).text();
If the response includes an XML declaration (<?xml version="...">
), use this instead:
shortURL = new XML(req.responseText.replace(/^<\?xml\s+version\s*=\s*(["'])[^\1]+\1[^?]*\?>/, "")).child(8).text();
精彩评论