0

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?

1
  • 1
    getElementsByTagName would return a node list. you have to traverse it using for loop or if there is only one element by that name, try using xmlGRP[0] Commented Aug 27, 2013 at 15:17

1 Answer 1

1
  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('');
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.