Javascript E4X:如何正确迭代属性 XMLList?
我在 javascript 中通过 E4x 检索属性值时遇到问题。
假设如下所示的 XML 节点列表作为 XMLObject:
<node att1="value1" att2="value2" att3="value3" att4="value4">
<nodeChild><!CDATA[/* ... */]></nodeChild>
/* more node childs */
</node>
我使用 attributes()
方法正确访问了节点(在循环中)及其属性节点:
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
}
现在,名称和值是未充分返回 value(n) 返回 name(n+1) 的值,即 att1
的值将是 value2
;如果我设置 var value = attribute[ (n+1) ].toString() ,则值会正确返回,但第一个值将返回未定义。
可能我只是对这个很感兴趣。那么,有人能指出我所缺少的内容吗?
蒂亚、
FK
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的代码对我有用,除了这些陷阱之外,我确信你的实际 XML 中不存在这些陷阱,因为你能够解析和迭代它们:
/* 更多节点子节点 */
使 XML 无效n
替换为 < code>0,或者完全不用它也可以。这是我用来迭代节点属性的确切代码。
请注意,E4X 提供了一种更简洁的方式来编写上述内容(结合 JavaScript 1.6):
由于您引用的是 XML 对象,因此无需像
node[0].您可以简单地编写
node
。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[..]]>
/* more node childs */
makes the XML invalidn
with0
, or could do without it altogetherHere's the exact code I used to iterate the node attributes.
Note that E4X provides a more succinct way of writing the above (combined with
for each in
introduced in JavaScript 1.6):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 writenode
.