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:
- CDATA declaration wasn't valid. Changed to
<![CDATA[..]]>
/* more node childs */
makes the XML invalid- Replaced
n
with0
, 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
.
精彩评论