0

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.

2
  • This is xsl syntax you have there, and it's most likely to respond with errors. Why don't you use regular xml tags like <p id="1234"> or <p><id>1234</id></p>? xsl is used to create xml templates. Commented Aug 11, 2017 at 13:16
  • That snip is from an XML document that is provided to me. I guess I could make edits to it but I would rather not if at all possible. Commented Aug 11, 2017 at 13:18

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, Christos. I can't believe I missed that. One little nugget can take a long time to figure out. Anyhow, thanks again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.