cbohannon
cbohannon

Reputation: 261

XML Node Value with Attribute

I am trying to retrieve a value from an XML node with an attribute using JavaScript. Here is an XML snippet.

<p:Header>
    <p:DocID>
        <p:ID>1234</p:ID>
    </p:DocID>
    <p:QualTerm type="SomeType">
        <p:ID schemeName="SomeScheme">5678</p:ID>
    </p:QualTerm>
</p:Header>

Here is a JavaScript snippet.

$.ajax({
    type: "GET",
    url: "http://localhost:8080/rest/getsomedata",
    contentType: "application/x-www-form-urlencoded; charset=UTF-8",
    data: id,
    dataType: "xml",
    cache: false,
    success: [
        function(data, textStatus, jqXHR) {
            var node1 = data.getElementsByTagName("p:Header");
            var id = data.getElementsByTagName("p:ID");

            for (var outerIndex = 0; outerIndex < node1.outerIndex; index ++) {
                for (var innerIndex = 0; innerIndex < id.length; innerIndex ++) {
                    var tag = data.getElementsByTagName("p:ID")[innerIndex];
                    var child = tag.childNodes[innerIndex];
                    var value = child.nodeValue;
                    alert(value);
                }
            }

            $("#footerMessage").find("span").remove();
            $("<span>Success! Data retrieved.</span>").appendTo("#footerMessage");
            console.log("Success! Data requested: " + data);
        }
    ]

I can retrieve the value of the first p:ID node just fine but the second time through the inner loop I receive an "undefined" value for for the second p:ID that has an attribute. How do I pull the actual value, 5678, from that second p:ID node? Thanks a bunch in advance for any assistance.

Upvotes: 0

Views: 161

Answers (1)

Christos Lytras
Christos Lytras

Reputation: 37327

The error is in this line here:

var child = tag.childNodes[innerIndex];

You always need to get the first child node of <p:ID> tag which contains the text ID, so, you'll always have to get it using this code:

var child = tag.childNodes[0];

It works for the fist element, because the first element is actually of 0 index.

Upvotes: 1

Related Questions