leodippolito@gmail.com wrote:
[color=blue]
> <?xml version="1.0" enconding="utf-8"?>
> <ReturnDocument>
> <ComboItem>
> <Key>1</Key>
> <Description>My first item</Description>
> </ComboItem>
> <ComboItem>
> <Key>2</Key>
> <Description>My second item</Description>
> </ComboItem>
> </ReturnDocument>
>
> */
>
> alert(objHttpRequest.responseXML); // alerts '[object XMLDocument]'
>
> var XmlDoc = objHttpRequest.responseXML;
>
> var arrTemp =
> XmlDoc.documentElement.getElementsByTagName("Combo Item");
>
> alert(arrTemp.length); // alerts '2'[/color]
So you can access the contents.
[color=blue]
> alert(arrTemp[i].childNodes[0].nodeValue); // alerts empty string[/color]
The first child node is a text node with whitespace, so that is what you
see.
[color=blue]
> alert(arrTemp[i].childNodes[1].nodeValue); // alerts 'null'[/color]
The second child nodes is the <Key> element node, element nodes do not
have a helpful nodeValue, so the null is all you get.
Instead of accessing the childNodes where you can get all kind of nodes
like text nodes, comment nodes, and that differs between browsers or
parser settings I strongly suggest to use getElementsByTagName if you
are looking for an element e.g.
var comboItems =
objHttpRequest.responseXML.documentElement.getElem entsByTagName('ComboItem');
for (var i = 0; i < comboItems.length; i++) {
var comboItem = comboItems[i];
var key = comboItem.getElementsByTagName('Key').item(0);
var description =
comboItem.getElementsByTagName('Description').item (0);
}
Now you have the element nodes and need to decide what information you
want, as you have seen MSXML in IE gives the whole text content with the
text property; Firefox has a similar property named textContent but
earlier versions of Mozilla do not implement that property; Opera so far
does not implement it either so in my view on the web it is best to
write a short helper function to collect text information e.g.
function getInnerText (node) {
if (typeof node.textContent != 'undefined') {
return node.textContent;
}
else if (typeof node.innerText != 'undefined') {
return node.innerText;
}
else if (typeof node.text != 'undefined') {
return node.text;
}
else {
switch (node.nodeType) {
case 3:
case 4:
return node.nodeValue;
break;
case 1:
case 11:
var innerText = '';
for (var i = 0; i < node.childNodes.length; i++) {
innerText += getInnerText(node.childNodes[i]);
}
return innerText;
break;
default:
return '';
}
}
}
Then in the above for loop you could use
var comboItem = comboItems[i];
var key = comboItem.getElementsByTagName('Key').item(0);
if (key) {
alert('Key has content: ' + getInnerText(key));
}
var description =
comboItem.getElementsByTagName('Description').item (0);
if (description) {
alert('Description has content: ' + getInnerText(description));
}
and that is going to work with all Mozilla browsers, with IE/Win using
MSXML, with Opera 8.
--
Martin Honnen
http://JavaScript.FAQTs.com/