XML Data by Name instead of childNode Array?

R

richard.morey

Hi --

I am trying my first attempt at parsing XML via JavaScript. I currently
have this code:

str =
"<RESPONSE><RESULT>SUCCESS</RESULT><SECURITY>10</SECURITY></RESPONSE>"
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.loadXML(str);
xmlObj = xmlDoc.documentElement;

I am getting the values for "RESULT" and "SECURITY" as below:


alert('xmlObj.childNodes(0).nodeName =
'+xmlObj.childNodes(0).nodeName)
alert('xmlObj.childNodes(0).text = '+xmlObj.childNodes(0).text)

alert('xmlObj.childNodes(1).nodeName =
'+xmlObj.childNodes(1).nodeName)
alert('xmlObj.childNodes(1).text = '+xmlObj.childNodes(1).text)

but I would like to be able to get the value for each field without
having to iterate through each child. Additionally, I would like my
code to be cross-browser compliant and from what I understand the
"text" property is only available on IE. When I try using "nodeValue"
it is always null.

Any insight would be greatly appreciated!

Rich
 
J

Joe Kesselman

but I would like to be able to get the value for each field without
having to iterate through each child.

Depending on the environment you're working in, you may be able to use
the DOM Level 2 traversal mechanisms, or the DOM Level 3 XPath support,
which can do that iteration for you... but those are optional features,
so it conflicts with your goal of being cross-browser compliant. Writing
your own loop to scan the kids really is the simplest solution.
"text" property is only available on IE. When I try using "nodeValue"
it is always null.

In the basic DOM, Element nodes have no value; you have to walk the tree
and gather the value of the contained text nodes. Again, some of the
optional features of later DOMs can help, but that conflicts with your
goal of interoperability.

Find a good DOM tutorial, and write a few convenience subroutines.
 
J

Joe Kesselman

I should add that DOM Element nodes do support the
getElementsByTagNameNS call ... but that searches all descendants, not
just the children, and it returns a NodeList which is arguably the
single most confusing corner of the DOM API. (For an idea of why I say
that, see http://www.w3.org/DOM/faq.html#nodelist -- which used to be
phrased even more strongly. I'm still convinced that NodeList was a
serious mistake in the DOM's design, but it was politically unavoidable.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top