Leon
Leon

Reputation: 3

Accessing XML node values with JavaScript

I have an XML file with the following structure:

<FIELDS>
    <GRP1>
       <OPTION>
            <VALUE>71</VALUE>
            <CONTENT>Text</CONTENT>
       </OPTION>
       ...
       ...
    </GRP1>
    <GRP2>
       <OPTION>
            <VALUE>77</VALUE>
            <CONTENT>Test</CONTENT>
       </OPTION>
    </GRP2>
      ...
      ...
</FIELDS>

I need to get the node values of all child nodes of <OPTIONS> with <GRP1> as parent node. I tried the following code but it did not work:

// [...]
var xmlGRP = xmlDoc.getElementsByTagName(GRP1);
xmlvalue = xmlGRP.childNodes[0].childNodes[0].firstChild.nodeValue;
xmlcontent = xmlGRP.childNodes[0].childNodes[1].firstChild.nodeValue;

Can anyone tell me what's wrong with my code?

Upvotes: 0

Views: 130

Answers (1)

bobince
bobince

Reputation: 536685

  1. Unless you have defined a variable called GRP1, that should be the string 'GRP1'.

  2. xmlGRP is directly a NodeList, not a Node; you don't need to look at a childNodes property on it.

  3. Accessing numbered childNodes is unreliable due to potential differences in whitespace handling.

  4. Accessing firstChild would fail for the case of empty string as the element would have no Text node child.

Try something like:

var grp1 = xmlDoc.getElementsByTagName('GRP1')[0];
var firstOption = grp1.getElementsByTagName('OPTION')[0];
var value = firstOption.getElementsByTagName('VALUE')[0].textContent;
var content = firstOption.getElementsByTagName('CONTENT')[0].textContent;

(Note that textContent is a DOM Level 3 Core property that isn't supported by IE 8 and below. If you need to support that browser you could use a workalike, eg:)

function getTextContent(node) { // not 100% DOM3 compliant... good enough
    if ('textContent' in node)
        return node.textContent;
    var texts = [];
    for (child = node.firstChild; child!==null; child = child.nextSibling) {
        if (child.nodeType===1) // ELEMENT_NODE
            texts.push(getTextContent(child));
        else if (child.nodeType===3 || child.nodeType===4) // TEXT_NODE, CDATA_SECTION_NODE
            texts.push(child.data);
    }
    return texts.join('');
}

Upvotes: 1

Related Questions