4

Obtain an XML element by index rather than Tag

 2 years ago
source link: https://www.codesd.com/item/obtain-an-xml-element-by-index-rather-than-tag.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Obtain an XML element by index rather than Tag

advertisements

I'm creating a video library and have an XML document split up by video category such as:

<video>
    <comedy>
        <url>bla</url>
        <title>blabla</title>
    </comedy>

    <action>
        <url>bla</url>
        <title>blabla</title>
    </action>
</video>

And so on. I use an XMLHttpRequest to getElementsByTagName() for the genre I want and it is working fine.

My question is: I want to create a 'Most Recent' category, that would just pick the first 16 (or however many) off the top of the XML file, regardless of category. Is there a way to accomplish this?


Iterate over the childNodes of the root-element, and check if the node is a element-node(childNodes will also return textNodes for the whitespaces)

var doc=xml,//the xml-document
            childs=doc.documentElement.childNodes,
               i=-1,
               j=16;//how many nodes you like to get

    while(j && childs[++i])
    {
      if(childs[i].nodeType===1)//check if we got a element-node
      {
        j--;
        //do something with the element
        console.log(childs[i].tagName);
      }
    }

In some browsers there may also be a children-property which only returns children that are element-nodes, but this is no standard so I wouldn't suggest to use it.

When you use a library like jQuery it would be much easier, to have the same result you only need:

$('>*:lt(16)',xml.documentElement)
  .each(function(i,o){console.log(o.tagName);});




About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK