Help - Search - Members - Calendar
Full Version: Getting only the childen of a XML node in javascript
HTMLHelp Forums > Programming > Client-side Scripting
Gooo
Hi

I am trying to read data out of a XML file into an array with javascript.

My Xml file contains many groups structured as follows:

CODE
<group>
        <groupName>The Real Friend</groupName>
    
<words>
        <word>fantasy </word>
        <word>violence </word>
        <word>world-illusion </word>
        <word>conspiracy </word>
        <word>schizophrenia </word>
        <word>childhood friends </word>

    </words>
    </group>


I want to get the groupName and then ONLY that group's words. I can get ALL the words and all the groups in the entire file by using
CODE
xmlDoc.getElementsByTagName("word").length
but then I don't know which words belong to which groups. The number of words for each group differ so I can't hard code that.

I am looking for something in javascript that is similar to java's

CODE
XMLElement group = xml.getChild(i);
    XMLElement words = group.getChild(1);
    int numWords = words.getChildCount();


Any ideas?
Christian J
Something like this?

CODE
var group=xmlDoc.getElementsByTagName("group");
for(var i=0; i<group.length; i++)
{
    var groupName=group[i].getElementsByTagName("groupName");
    if(groupName[0].firstChild.nodeValue=='The Real Friend')
    {
        var word=group[i].getElementsByTagName("word");
    }
}


See also http://www.quirksmode.org/dom/w3c_core.html

Edit: fixed an error.
Gooo
Thanks!

It might work, but there is an unending amount of groups, so I can't really spesify the group name in the if.

What if I change it to something like this?

CODE
var group=xmlDoc.getElementsByTagName("group");

for(var i=0; i<group.length; i++)
{
    var groupName = group[i].getElementsByTagName("groupName").nodeValue;
    
    if(groupName.firstChild.nodeValue== groupName)
    {
        var word=group[i].getElementsByTagName("word");
    }
}


Only now groupname is undefined. How can I get it's value?
Gooo
Fixed it!

CODE
var group=xmlDoc.getElementsByTagName("group");

for(var i=0; i<group.length; i++)
{
    var groupName = group[i].getElementsByTagName("groupName");
    var groupNam = groupName[0].childNodes[0].nodeValue;
    
    document.write(groupNam + "<br/>");
    
           var word=group[i].getElementsByTagName("word")
        
        for(var j=0; j<word.length; j++)
          {
           var w = word[j].childNodes[0].nodeValue;
        document.write("!" + w);
        }

}
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2009 Invision Power Services, Inc.