简体   繁体   English

具有属性的XML节点值

[英]XML Node Value with Attribute

I am trying to retrieve a value from an XML node with an attribute using JavaScript. 我正在尝试使用JavaScript从具有属性的XML节点检索值。 Here is an XML snippet. 这是一个XML代码段。

<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. 这是一个JavaScript代码段。

$.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. 我可以很好地检索第一个p:ID节点的值,但是第二次通过内部循环,我收到了具有属性的第二个p:ID的“未定义”值。 How do I pull the actual value, 5678, from that second p:ID node? 如何从第二个p:ID节点提取实际值5678? Thanks a bunch in advance for any assistance. 预先感谢您的协助。

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: 您始终需要获取<p:ID>标签的第一个子节点,其中包含文本ID,因此,您始终必须使用以下代码来获取它:

var child = tag.childNodes[0];

It works for the fist element, because the first element is actually of 0 index. 它适用于fist元素,因为第一个元素实际上是0索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM