0

Given the following xml

<rss>
    <channel>
    ...
    <pubDate>20/30/2099</pubDate>
    ...
    <item>
        ...
        <pubDate>10/30/2099</pubDate>
        ...
    </item>
    ...
    <item>
        ...
        <pubDate>40/30/2099</pubDate>
        ...
    </item>
    ...
    </channel>
</rss>

how would I efficiently access pudDate in channel and items as array, as well as pudDate in that array.

4
  • which server-side language are you using? Commented May 2, 2010 at 7:41
  • @Sarfraz: it's actually client side javascript, specifically going to use in firefox extension. Commented May 2, 2010 at 7:45
  • Figured out that can get items collection with var items = xmlDoc.getElementsByTagName("item"); However, can't believe I have to iterate through each element and check the tag name... Commented May 2, 2010 at 8:00
  • or I have to rely on the order of the elements and use indexes? Commented May 2, 2010 at 8:18

1 Answer 1

1

You could use xpath (as long as you don't need it for IE), using document.evaluate. Here's the function I use for it:

 function getFromXPath(expression,rootEl){
   rootEl = rootEl || docbody;
   var ret = [] 
             ,xresult = document.evaluate(expression, rootEl, null,
                         XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null)
             ,result = xresult.iterateNext();
   while (result) {
     ret[ret.length]= result;
     result = xresult.iterateNext();
   }
   return ret;
}

Where in your case expression could be something like "//channel/pubdate|channel/item/pubdate" (for all pubdates in the tree) or "//chanel/items" (for all item elements in the tree), and rootEl being the (xml) document root.

This function returns an array containing the elements you requested by xpath-expression.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.