Javascript / XML - 获取节点名称 [英] Javascript/XML - Getting the node name
问题描述
我需要获取标签myChild和内容的名称。
这很简单,但我很困惑,困倦,这里是我通过测试得到的:
I need to get the the name of the tag "myChild" and the "content". This is simple, but i am stuck, sleepy and here is what I get with my tests:
XML:
...
<myParent>
<myChild>content</myChild>
</myParent>
<myParent>
<myChild>content</myChild>
</myParent>
...
JS:
var x=xmlDoc.getElementsByTagName("myParent");
alert(x[1].childNodes[0].nodeName); //returns "#text" - "myChild" needed
alert(x[1].childNodes[0].nodeValue); //returns "" - "content" needed
推荐答案
s>你想要 tagName
,这是元素的名称。 (对不起,对于元素
s, tagName
和 nodeName
是一样的。)
You want (Sorry about that, for tagName
, which is the name of the element.Element
s, tagName
and nodeName
are the same.)
问题是您的 myParent
元素的第一个孩子不是 myChild
元素,它是一个文本节点(包含空格)。您的结构如下所示:
The problem is that the first child of your myParent
element isn't the myChild
element, it's a text node (containing whitespace). Your structure looks like this:
- 元素myParent
- 回车和一些空格或制表符
- 元素myChild
- 带有内容的文本节点
- 带回车符和一些空格或制表符的文本节点
- 元素myChild
- 带有内容的文本节点
您需要导航到实际的
myChild
元素,您可以再次使用getElementsByTagName
或仅通过扫描:You need to navigate down to the actual
myChild
element, which you can do withgetElementsByTagName
again, or just by scanning:var x=xmlDoc.getElementsByTagName("myParent"); var c = x[1].firstChild; while (c && c.nodeType != 1) { // 1 = ELEMENT_NODE c = c.nextSibling; } alert(c.nodeName); // "myChild"
请注意,
元素
s没有有意义的nodeValue
属性;而是收集他们的子文本节点。 (更多DOM规范: DOM2 , DOM3 。)Note that
Element
s don't have a meaningfulnodeValue
property; instead, you collect their child text nodes. (More in the DOM specs: DOM2, DOM3.)另外请注意,当索引到
NodeList
时,索引从0
开始。您似乎已经开始使用1
;忽略这个评论,如果你是因为某个原因跳过了第一个。Also note that when indexing into a
NodeList
, the indexes start at0
. You seem to have started with1
; ignore this comment if you were skipping the first one for a reason.离线主题 :总是最好了解你正在使用的底层机制,我建议您使用直接的DOM,并参考上面列出的DOM规范。但是,为了与这些树进行交互,一个好的图书馆可以真正有用,节省了大量的时间。 jQuery 适用于XML数据。我没有使用任何其他人,如原型, YUI ,关闭或其他任何一个使用XML,所以不能说,但我预计至少有一些支持它。
Off-topic: It's always best to understand the underlying mechanics of what you're working with, and I do recommend playing around with the straight DOM and referring to the DOM specs listed above. But for interacting with these trees, a good library can be really useful and save you a lot of time. jQuery works well with XML data. I haven't used any of the others like Prototype, YUI, Closure, or any of several others with XML, so can't speak to that, but I expect at least some of them support it.
这篇关于Javascript / XML - 获取节点名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!