开发者

Javascript E4X: How do I properly iterate over an attribute XMLList?

开发者 https://www.devze.com 2023-01-04 23:15 出处:网络
I have a problem with retrieving attribute values via E4x in javascript. Suppose a list of XML nodes like the following as the XMLObject:

I have a problem with retrieving attribute values via E4x in javascript.

Suppose a list of XML nodes like the following as the XMLObject:

<node att1="value1" att2="value2" att3="value3" att4="value4">
    <nodeChild><!CDATA[/* ... */]></nodeChild>
    /* more node childs */
</node>

I properly accessed the nodes (in a loop) and its attribute nodes using the attributes() method:

var attributes = node[n].attributes() ;
    for(var n = 0 ; n < attributes.length() ; n++) {
        var name = attributes[n].name() ;
        var value = attributes[n].toString() ;
        //.. handle the values
    }

Now, for one, names and values are not adequately returned value开发者_高级运维(n) returns the value of name(n+1), i.e. the value of att1 will be value2 ; if I set var value = attributes[ (n+1) ].toString() the values are returned correctly but the first value will return undefined.

Possible I'm just dense on this one. So, does anyone have any pointers to what I am missing?

TIA,

FK


Your code works for me, apart from these gotchas which I'm sure don't exist in your actual XML since you are able to parse and iterate through them:

  1. CDATA declaration wasn't valid. Changed to <![CDATA[..]]>
  2. /* more node childs */ makes the XML invalid
  3. Replaced n with 0, or could do without it altogether

Here's the exact code I used to iterate the node attributes.

var node = <node att1="value1" att2="value2" att3="value3" att4="value4">
    <nodeChild><![CDATA[/* ... */]]></nodeChild>
</node>;

var attributes = node[0].attributes() ;
for(var n = 0 ; n < attributes.length() ; n++) {
    var name = attributes[n].name() ;
    var value = attributes[n].toString() ;
    console.log("%s = %s", name, value);    
}

// log output
// att1 = value1
// att2 = value2
// att3 = value3
// att4 = value4

Note that E4X provides a more succinct way of writing the above (combined with for each in introduced in JavaScript 1.6):

for each(var attribute in node.@*) {
    var name = attribute.name();
    var value = attribute.toString();
}

Since you are referring to an XML object, there is no need to reference the root element by index as in node[0]. You can simply write node.

0

精彩评论

暂无评论...
验证码 换一张
取 消