how to retrive the elements of array.

S

sunsmurf

Hi

I'm a JavaSCript newbee and i've got a problem.

I do a search and get the following in xml:

<user>
<exec>
<entry>Value1</entry>
<entry>Value2</entry>
<entry>Value3</entry>
<entry>Value4</entry>
<exec/>
<user/>

How is the easiest way to find the number of entries in the array and
how can iterate over each value to test if the given value matches
another variable?

Thanks
JT
 
L

lallous

Hello,

This is not the optimal solution:

<script>

var s=
'<user>'+
' <exec>'+
' <entry>Value1</entry>'+
' <entry>Value2</entry>'+
' <entry>Value3</entry>'+
' <entry>Value4</entry>'+
' <exec/>'+
'<user/>';

var i, j, entry;
while(true)
{
i = s.indexOf('<entry>');
if (i == -1)
break;
s = s.substr(i+7); // chop off <entry>
j = s.indexOf('</entry>');
entry = s.substr(0, j);
alert(entry);
}
</script>
 
T

Thomas 'PointedEars' Lahn

sunsmurf said:
I do a search and get the following in xml:

<user>
<exec>
<entry>Value1</entry>
<entry>Value2</entry>
<entry>Value3</entry>
<entry>Value4</entry>
<exec/>
<user/>

How is the easiest way to find the number of entries in the array

Get the `exec' element an ID, then access it using

document.getElementById("execElementID")

Otherwise you need to access the element using the collection

document.getElementsByTagName("exec")

returns.
and how can iterate over each value to test if the given value
matches another variable?

Provided the element has the ID `execElementID':

var o = document.getElementById("execElementID");

Or, if it is the first/only `exec' element:

var o = document.getElementsByTagName("exec")[0];

You can always use:

if (o)
{
for (var i = 0; i < o.childNodes.length; i++)
{
if (o.childNodes.nodeValue == foobar)
// do something
}
}

Untested, read http://www.w3.org/TR/DOM-Level-2-Core/ for details.


PointedEars
 
S

Steve van Dongen

Hi

I'm a JavaSCript newbee and i've got a problem.

I do a search and get the following in xml:

<user>
<exec>
<entry>Value1</entry>
<entry>Value2</entry>
<entry>Value3</entry>
<entry>Value4</entry>
<exec/>
<user/>

How is the easiest way to find the number of entries in the array and
how can iterate over each value to test if the given value matches
another variable?

If you only care about MSXML you can do both at the same time.

var lookupValue = "Value1";
var dom = new ActiveXObject("MSXML2.DomDocument.4.0");
dom.async = false;
dom.loadXML(<xml string>);
var nodes = dom.selectNodes('/user/exec/entry[. = '" + lookupValue +
"']);
alert(nodes.length);
alert(nodes.item(0).text);

Regards,
Steve
 

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

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,165
Latest member
JavierBrak
Top