Javascript/XML - Getting the node name

2020-04-12 00:37发布

问题:

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

回答1:

You want tagName, which is the name of the element. (Sorry about that, for Elements, tagName and nodeName are the same.)

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:

  • Element "myParent"
    • Text node with a carriage return and some spaces or tabs
    • Element "myChild"
      • Text node with "content"
    • Text node with a carriage return and some spaces or tabs
  • Element "myParent"
    • Text node with a carriage return and some spaces or tabs
    • Element "myChild"
      • Text node with "content"
    • Text node with a carriage return and some spaces or tabs

You need to navigate down to the actual myChild element, which you can do with getElementsByTagName 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"

Note that Elements don't have a meaningful nodeValue property; instead, you collect their child text nodes. (More in the DOM specs: DOM2, DOM3.)

Also note that when indexing into a NodeList, the indexes start at 0. You seem to have started with 1; ignore this comment if you were skipping the first one for a reason.


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.



回答2:

Try x[1].getElementsByTagName('*')[0] instead.

(This is only trustable for index 0, other indexes may return elements that are not child-nodes, if the direct childs contain further element-nodes. )