Search code examples
xmlflashparsingxhtmlactionscript-2

Parsing XML/XHTML in ActionScript


Is there anything similar to getElementById in ActionScript?

I'm trying to make a prototype of a flash page which gets it's data from a xhtml file. I want to have both an accessible html version (for search engines, textreaders and people without flash) and a flash version (because the customer insists to use flash even though a html-css-ajax solution would do quite nicely).

What I need is a simple way of getting the text or attributes from the html with a certain id, like <h1 id="flashdataTitle">This is the title</h1> etc. I'm guessing a few ways it might be possible:

  • Somehow use an ExternalInterface.call and do the DOM trickery in JavaScript (which is probably what I will do, because I'm very familiar with JS and a complete newbie with flash/ActionScript, unless you have a better solution)
  • Load the xhtml with the ActionScript XML class, and manually traverse the XML looking for the correct id attribute (but this is probably very slow)
  • Use XPath with the XML class in ActionScript. (I'd like some hints on how to do this, if this is the recommended way)
  • There is actually an ActionScript equivalent to getElementById to use with the XML?
  • Although my employer hope we don't have to do this: I could rewrite the server side code to output the relevant texts and image URLs in a flash-friendly format.

What is the most effective, easiest to implement, and robust-cross browser way of doing this? Any totally different ideas?

Please post any ideas even if you think the question have been answered, I'd like to explore all the different possibilities, and also what disadvantages the proposed solutions have.


Solution

  • Since you said your input would be XHTML, you can do it with XPath:

    import mx.xpath.XPathAPI;
    
    var elementId:String = "flashdataTitle";
    var elementPath:String = "//h1[@id'" + elementId + "']";
    found_elements = XPathAPI.selectNodeList(xhtml.firstChild, elementPath);
    
    if (found_elements.length == 1) {
      trace(found_elements[0]);
    }
    

    The code example is inspired from here, where you also can find some mode detail on XPath and ActionScript.

    AS3 has it's own XPath Library, the general approach would be the same.