You are on page 1of 17

AS3 E4X Rundown | dispatchEvent

Página 1 de 17

dispatchEvent
Welcome to dispatchEvent, a blog brought to you by Mims Wright of losdesigns and Roger Braunstein of partlyhuman. « The ActionScript 3.0 Bible Cometh Apollo FileSystem Tutorial Part 1 - File and FileStream »

AS3 E4X Rundown
by Roger Braunstein
View this article in other languages: Chinese translation by Wei Gao

I've been using E4X in ActionScript 3.0 for a while now and the rumors of its simplicity have been greatly exaggerated. A lot of operations are easy and make sense, but others are less... obvious. E4X is essentially a whole new language which is part of the AS3 grammar, just as regular expressions have their own completely different language but exist within ActionScript 3.0. And being so new, there really isn't a whole lot of documentation out there. This is further complicated by the fact that since E4X seems simple enough at first glance to explain in a few lines, a lot of documentation stops short. Anyway. I've been infuriated by E4X more than a few times now, and I'd like to start a running post to demystify some of it. Please! use the comments to ask any questions you might have, and I'll keep adding to this post. Hopefully this can turn into a decent resource for E4X lore. The fun begins after the cut. For the following post, let's use this XML block as an example:
var thePeople:XML = <people> <person name="Mims Wright" suffix="III"> <age>27</age> <aka>Mims H Wright</aka> <aka>Teh AWesoeomes!</aka> <bio><![CDATA[This guy <b>rulz<b>!]]></bio> </person> <person name="Roger Braunstein"> <age>26</age> <aka>Rog</aka> <aka>That guy</aka> <bio><![CDATA[Likes food.]]></bio> </person> </people>;

XMLList vs XML
Ok, first thing you notice is that you can just type in XML and it becomes an XML typed variable. You should also know that this XML class is not the same as the XML class in AS2. All new! Second thing you should know is that there are two principally related classes: XML and XMLList. XML is well-formed XML (mostly; see Node Types for exceptions). XMLList is a list of XML nodes. The difference here is that XML must always have one single root node; XMLLists have multiple nodes at the base depth. For instance, the whole example above is XML because it is typed as XML and it has a single root node, <people>. In contrast, an XMLList is composed of zero or more root nodes, like:
<age>27</age> <age>26</age>

This can't be XML because there are two root nodes. You can, however, think of it as a list of XML, since each <age> node is itself a single root node. It's important to note that an XMLList can also have one (like XML) or zero nodes. Anyway, most of the basic operations for E4X are filtering operations. You take the XML and find some subset of the XML. Often, you want to find a particular node. Any filtering you do is going to result in a number of possible nodes, so you will notice soon that XML always turns into XMLList when you filter it. Most of the time you'll be dealing with XMLLists. The same kinds of filters are available on both classes, except where noted.

The Basics
These are the basics of E4X. You've probably figured these ones out already cuz you is a pimp!
thePeople.person.age

http://mimswright.com/blog/?p=141

15/02/2008

but the result is an XMLList of attributes. The first one gets you all the <person> nodes immediately below the root node.AS3 E4X Rundown | dispatchEvent Página 2 de 17 Use dot syntax to select child nodes by name. This expression returns an XMLList with both Mims and I because we're both totally legal drinking age AWESOME! Another expression you could create: thePeople.person. the expression goes from XML→XMLList→XMLList→XML→XMLList→XML. The result of this query is: <age>27</age> <age>26</age> We didn't bother to look for the <person> tags. a parenthetical can filter nodes based on arbitrary criteria. //XMLList with one node thePeople. Result: <person name="Roger Braunstein"> <age>26</age> <aka>Rog</aka> <aka>That guy</aka> <bio><![CDATA[Likes food.(@name == "Roger Braunstein")[0]. //XML I think it's kind of unfortunate that there's no shortcut to pick the only result of a filter. you could find all <div> tags in an XHTML document this way. the result is not a list of nodes but a list of attributes. thePeople.com/blog/?p=141 15/02/2008 .. This time. thePeople. This will print out "complex content" like XML and "simple content" like its string value.person. It lets you search for descendents instead of children. since all filters available to you return all possible matches. but we'll talk more about node types later. or a single XML element with no XML node children (such as <age>26</age>).person.]]></bio> </person> Also. this line would return it as well as the <age> nodes under the <person> nodes. Alternately. those <age> tags can come from anywhere in the XML. The variable is already associated with the root node so there's no need to write <people> into the expression.person[1] Use square brackets to get XML nodes out of XMLLists. This example is two subsequent filters. in other words. The second one gets you all the <age> nodes below all the nodes in the first filter. when searching out a specific node you'll use this all the time. thePeople. but you might find yourself picking out the first result of every test. The first finds all the <person> nodes under the root. This is your way to get from XMLList to XML. //Roger's <person> node thePeople. The expression above has two successive filters.g.person. This means you can print out my age with: http://mimswright.. thePeople. thePeople.person. If the example had a non-<person> tag with an <age> child. because complex E4X expressions can frequently become polluted with [0]s. attribute nodes.charAt(0) == "R"). For example. It doesn't care what the first generation child is. and the second finds all the name attributes of those nodes. and notice how it retrieves all the age nodes under all the person nodes.) finds all the applicable nodes that are at any depth rather than at the the next depth. an XMLList.(@name == "Roger Braunstein").age The asterisk operator (*) selects all children of the node. toString() is called.(@name. In the second example above. Result: <age>27</age> <age>26</age> Again. It gets weird here.. E. For instance. you can create a sequence of filters that should only have one match. if you don't specify a different conversion function. this is an XMLList. This sure isn't valid XML.age Using two dots instead of one (.*.age.age[0]. You can use hasSimpleContent() and hasComplexContent() to test these: simple content are text nodes. you can just place one at the end of a chain of filters. like an indexed array.(age >= 21) Possibly your most powerful tool. as long as the second generation child is <age> Strings and XML When you're printing out XML elements.@name Use the @ symbol to select attributes instead of child nodes.

but since they're both text nodes. and the like.toString() prints out its text value. toXMLString() does. even if corresponding properties in other classes are implemented as implicit accessors. and the second retrieves a list of all attributes.person.person[0]. and is the same as typing that name in literally. and XMLList. children() These axes find the children of the given node[s]. The first finds a child of a specific name. If you want to ensure that the content prints out like XML. list of all suffix attributes thePeople. E4X loses out on axes big-time.age). //2 All the tests and filters are implemented as functions.person. We could extract a list of all of the text nodes inside all the age tags with the following: trace(thePeople.AS3 E4X Rundown | dispatchEvent Página 3 de 17 trace(thePeople.(@name == "Roger Braunstein"). use toXMLString(). Those were actually shortcuts for more verbose functions. and z. //ERROR!!! thePeople.@name). In the basics.age. sibling nodes. an XML node with a text child.age. calculated properties. We want to be able to name XML nodes anything we want. Important! The attribute(name) axis will frequently serve you better than the @name shortcut! The shortcut only works when the attribute exists on all nodes in the list. //OK. attribute(name). It's missing several important ones. grabbing an attribute like thePeople. so all the filters. y. and functions of XML nodes are implemented as functions. The first filters by the name of the attribute.children() == thePeople. Mims' node child(name). For instance.person returns a text node.(@name == "Roger Braunstein"). trace(thePeople.text()[0]). and we use array access to grab the first one. using a property name in an expression finds child nodes with the specified name. Their shortcuts are @name and @*.length(). like thePeople. however. attributes() These axes find attributes of the corresponding XML. which we've seen before as the asterisk operator.(@suffix == "III").@suffix. The same applies for: trace(thePeople. thePeople. //<age>26</age> [0].person. thePeople. that list happens to have just one element. XPath comparison.person. this filter returns an XMLList of all the text nodes found.person[0]. it prints out as: 27 26 Function-style Properties In E4X. This is a huge limitation.length would look for <length> nodes in the XML.child("*") == thePeople. //27 Again. In space. Synonyms. //26 Even though this expression returns an XMLList. by child I mean a first-generation descendent. //OK. but we can find the number of <person> nodes with: thePeople.com/blog/?p=141 15/02/2008 . //Mims Wright Use toString() as a simple way to get text content out of attributes and simple XML containers like <age>26</age>.text()).person. The following holds true: thePeople.toXMLString()). In other words.@name You can use the text() filter to grab text nodes out of XML.person.person. 26.* http://mimswright. Other Axes An "axis" is a direction of movement. In the E4X vs.. //2726 Note that toString() doesn't add any space. trace(thePeople. I covered a bunch of directions you can travel already. The only child of <age>26</age> is a text node. In XML. The second finds all children. and a good reason to use the function version. we can travel over the axes x.(attribute("suffix") == "III"). we can travel down to child nodes. This list will show which shortcuts exist.age.

comment. //in general.@name).parent().age = 80. //all siblings node.child(interestedNode).person[0].descendants() == thePeople. //Mims' bio You can also pass an index to child() to retrieve a child at a certain index. For instance: var age0:XML = thePeople. var nodeName:String = "age". as well.person." or "processinginstruction.random() * 100)}</{nodeName}>. descendants(name) This axis returns all descendants (children. but node names and whole nodes. this axis has one function.) is also missing from E4X. //previous sibling The ancestor axis (parent. just like using the array access notation.descendants("age") thePeople. siblings would be really nice. //sets my age to 80 thePeople. grandparent. //Mims Wright Do you notice what's missing? Yes. Node Types In addition." "text.person[1].parent(). This is my workaround for sibling traversal. //ERROR! you can't set multiple elements with one assignment thePeople." "comment. It will return "element.parent().descendants("*") parent() This axis returns the node's parent or nodeset's immediate parents. grandchildren. //<age>27</age> trace(age0. var node:XML = thePeople. or processing instruction.*[node.).person[0]. You can use the nodeKind() function to identify the type of a node. "Bob".* == thePeople.AS3 E4X Rundown | dispatchEvent Página 4 de 17 There are benefits to using this (and all the filters) as axis functions rather than shortcuts. "Ivan"]. var names:Array = ["Alice". var newAge:XML = <{nodeName}>{Math. and they are writable! So you can change attributes and elements that already exist: thePeople.age = 80. In other words. thePeople. you'll end up with an XMLList object or XML object. http://mimswright. You can use stored values and expressions as not only attribute names. for any node: node. etc.) of a node set whose node name matches the name passed.random() * names.. This means that XML typed variables aren't always valid XML documents. as we've seen. great-grandparent. it will return all the descendants. var interestedNode:String = "bio". These objects are always pointers to the original data (unless you use copy() to clone them).age[0].. Unlike child() and children(). There is no shortcut for this.*[node. it defaults to *.age == thePeople. E4X lets you embed variables in XML literals using curly braces: var names:Array = ["Alice".. Let me know if you have a better one. there are axes which select specific kinds of nodes. by literally typing them in. thePeople.round(Math. Its shortcut is the double dot (. but if a name is not passed. The elements(). In my opinion this is more confusing than helpful.person[1].parent().". Creating and Updating Values When you select nodes with a filter chain. In addition. an XML instance can hold a node of any type: element. A text node by itself is not valid XML. var newPerson:XML = <person name={names[int(Math.@suffix = "Sr. text(). //next sibling node.childIndex() + 1]. etc.1].. "Ivan"]. The major benefit is that you can use a variable name as the parameter to an axis function. text. you have to hack your way around this by going to the parent and finding the next index." Note also that processing instructions and comments are typically ignored unless you change those settings on the XML object.length)]}></person>. It was so easy in AS2 to use nextSibling and previousSibling. comments(). You can create new XML nodes. But believe it or not.com/blog/?p=141 15/02/2008 . and processingInstructions() axes select nodes of these types as children.childIndex() . In actuality.children(). //set my suffix to Sr. "Bob".

Whereas opening a namespace allows you to read in XML in that namespace. Why?!? thePeople. and that's the construct default xml namespace. There's one odd addition to the language that's specified in the E4X spec.(@name == "Roger Braunstein"). but instead of just changing the type annotation.person. default xml namespace = xhtml. This is kind of cracked out: var aliases:XMLList = <> <aka>Elmo</aka> <aka>The Fonz</aka> <aka>Peanut Butter</aka> </>. These methods take the Object type because they will attempt to convert their argument to a String and insert it as text if you don't pass XML. the delete operator is your only way to remove values. insertChildBefore().aka += <aka>Rog</aka>.com/blog/?p=141 15/02/2008 .appendChild(<aka>Von Kaiser</aka>).org/1999/xhtml"). Adding Values There are many ways to append values to existing XML. //<html xmlns="http://www. trace(xml. var xml:XML = XML(xmlString). //clears out children of my node Namespaces I can write more about namespaces in a future revision. But pass XML. it performs a conversion.*. //Doesn't work but no error. You can use delete with a single node or a whole XMLList. and it will work as you might expect: thePeople.@suffix.@type).w3..person[1].person[1]. var xml:XML = <html/>.w3. there are a lot of shortcuts that sometimes make sense and sometimes not.. thePeople. //delete all <bio> tags thePeople. like pushing to an array by assigning to the first vacant index.device[0].bio. You can also immediately set non-extant values to create them. //notice we didn't set a namespace manually trace(xml.AS3 E4X Rundown | dispatchEvent Página 5 de 17 var newPerson:XML = <person name={names[int(Math.person[1].* += <eyes>Brown</eyes>.length)]}> {newAge} </person>.. and insertChildAfter() methods.(@name == "Mims Wright"). The += operator is overridden for XMLLists. //usb http://mimswright. delete delete delete delete thePeople.person. or an attribute. so you can use this as a quick way to append nodes: thePeople. but for now check out the good discussion started in my previous post. //deletes all suffix attributes of <person> tags thePeople. var xhtml:Namespace = new Namespace("http://www.org/1999/xhtml"/> Loading External Data You can convert any String to XML by using the top-level XML() function. //adds <eyes>Green</eyes> to Mims' node. thePeople.person.toXMLString()).person[0]. You can create XMLList literals by using a root tag with no node name.eyes[0] = "Green". This looks like a cast operator and acts like one as well: it converts its argument to the XML type. Deleting Values There is no corresponding removeChild() method. Using E4X? Watch Your Namespaces. thePeople. setting a default XML namespace will also implicitly apply that namespace to new nodes you create. Say I want to add an alias to my name. As with the rest of E4X. Instead. Perhaps a more sensical way to insert new nodes into existing XML is to use the appendChild().connection.children() += <test>hi</test>.person. You can use this function to get XML from other functions and variables: var xmlString:String = '<root><device name="mouse" buttons="2"><connection type="usb"/></device></root>'. //ERROR! I'm not sure why the last line doesn't work.random() * names.bio.

even some of the newer flex books don’t even talk about e4x.certainly native XML and XML literals are excellent.addEventListener(Event.toXMLString()).data). VT Says: May 21st. 2007 at 7:33 am Thanks. i’ve struggled with that stuff for days. especially if you have any problems! Note: If you are going to include XML in your comment.COMPLETE.target). bobbaganoosh Says: May 23rd. var loader:URLLoader = new URLLoader(new URLRequest("http://partlyhuman. it will not work if you don’t: private namespace wtf = “http://bla. Createage . function onLoadSuccess(event:Event):void { trace("Loaded successfully!"). } function onLoadFailure(event:Event):void { trace("Error loading file: " + event. var loader:URLLoader = URLLoader(event. 4. onLoadFailure). trace(xml. the reasoning behind creating a whole new language for filtering when we have existing languages such as XPath and the Selectors API is that they are too difficult to learn. 2007 at 1:06 am I’m glad to see someone put in writing that E4X is just not that simple. May 21st. please add your comments. You can follow any responses to this entry through the RSS 2. 2007 at 8:21 pm […] http://www. please convert the tags to HTML entities or they will be eaten! Use this tool.0 feed.com/blog/?p=141 15/02/2008 . This entry was posted on Monday. I'm certainly happy that there's some native XML support in AS3. and I think it's not doing AS3 any favors to try to gloss this over. and a possible useful addition: When using soap you have to switch to the correct name space. still doing things the old way.addEventListener(IOErrorEvent. var xml:XML = XML(loader. Check out the documentation for more info on how to use this class.AS3 E4X Rundown | dispatchEvent Página 6 de 17 You can also use it to load data from an external file with the URLLoader class. You can leave a response. Programming. loader. 2007 at 8:27 am yes. } Conclusion 75% of what you'll need to do with E4X is simple. But according to ECMA. Stefan Says: May 24th. I'm really not sure adding E4X was a great idea -.type). onLoadSuccess).IO_ERROR. Again. use namespace wtf. http://mimswright. 2007 at 8:44 pm Thanks for the post. or trackback from your own site.i’m in the same situation and all the docs i’ve ever seen just say that e4x is so darn easy that it seems a good explanation is not necessary.com/crossdomain. 62 Responses to “AS3 E4X Rundown” 1. but let's be serious about explaining it. loader. I can’t wait to work with XML using E4X! 3. 2007 at 8:07 pm and is filed under AS3.com/blog/roger/as3-e4x-rundown […] 2. It’s a better way of doing things but there are certain things about it that one would not “just figure out”. thank you.xml")). 5.com”.com » Good E4X Info from Roger Says: May 21st. diamondTearz Says: May 22nd. but there are a bunch of gotchas.partlyhuman. and not "simple" enough.your post is a big help.

day) { var d:Date = new Date(month. Is what I was looking for. This code could go through all of the entries in order: for each (var month:XML in xml.@year.day. } } Or this takes the last one: xml. month. But how to get to the last node attributes if the last mode is constantly changing? 8.. 2007 at 7:27 am This is great. Jeff Says: June 1st. trace(day.xml. Roger Braunstein Says: May 24th. thanks! I will post more about namespaces in a bit. 2007 at 6:06 pm xml.day[xml.month[0].30) Accessing the beginning of the month is easy enough: startDate = new Date(xml..com/blog/?p=141 15/02/2008 . 2007 at 4:01 pm @Stefan.@date). Hehe. <day date="30" impressions="657"/> </month> </list> More months will be added with time so I need to set a variable always with the values of the lastest month: endDate = new Date(2007.5.1]..length() .@month ..day.day[xml. </month> <month month="4" year="2007"> etc.1].. I was getting tired of typing and I covered it a little bit in the linked article .month[0].xml.@impressions + " impressions on " + d).length() .. moca Says: May 28th. thanks a lot! But what about something like this? This is my xml: <list> <month month="3" year="2007"> <day date="01" impressions="407"/> etc.day[0].. Thanks a lot! 10. moca Says: May 29th.1.AS3 E4X Rundown | dispatchEvent Página 7 de 17 6. 2007 at 12:20 am http://mimswright. day. 9. Roger Braunstein Says: May 29th. 7.@month. 2007 at 12:56 pm Badass! 11.@date).) I’ll stop being lazy though.month[0]. 2007 at 12:36 am Hey Moca..month) { for each (var day:XML in month. Jim Kremens Says: June 9th..@year.

you don’t know what you’re looking for . You can use code from the JSON library in Adobe Labs’ core library to do that work for you. then store those real values back in the same XML. in most cases.AS3 E4X Rundown | dispatchEvent Página 8 de 17 I’ve come across another annoying issue that you briefly alluded to . I often work with externally loaded data where the attributes look something like this: colors="[0x666666.com/blog/?p=141 15/02/2008 . Typically. No. when working with the XML.the weird typing of attributes in E4X. but I might still be missing some…] 12. though. but I think the answer is for me to rewrite this particular section of code so it doesn’t rely on specious coding practices… http://mimswright. Number(hatSize) + 1). you still have to convert everything from strings. Then. This is certainly one weakness of the format. Because I was able to do this. when it comes down to it. However. Here’s an example. you used to be able to eval() them to interpret them as the AS2 interpreter would as code. hatSize is XMLList. But say. 2007 at 2:23 pm Hi Roger. You can retrive the value and cast it to number. 100]" ratios="[0.person[0]. or whatever. a real array. 0xFFFFFF]" alphas="[100. If you typed things in JSON-style. I did. trace(hatSize. It was possible to convert attributes and node values into real objects (from strings) in AS2. hatSize + 1.you just want to throw the JSON at the class for configuration purposes. It is indeed a limitation of the format. 13. like hatSize. turn them into real objects. but it turns out to be an XMLList! var thePeople:XML = 27 Mims H Wright Teh AWesoeomes! rulz<b>!]]> var hatSize:XMLList = thePeople. that…. turn all of the values from strings into real values using a JSON parser. the number 8 is an XML List… Makes perfect sense! :-) I think it’s important to be able to know the type of an attribute value. If you know what you’re looking for. So. 2007 at 2:59 am Hey Jim. In AS2 I was able to pull in a piece of XML. The problem I’m having is one of workflow. I added a ‘hatSize’ attribute. I could be sure that I had a real number. Roger Braunstein Says: June 11th. However. and insert them back into the attributes object. for example. this isn’t a big deal. 75]" matrix="{big object here} In AS2.attribute("hatSize"). but doesn’t seem to be possible in AS3/ E4X. a real object. there’s no way for E4X to divine what kind of data is stored in attributes or text nodes. Starting with your blob of XML above. you’ll know that the hatSize attribute is meant to be a number. You might expect that attribute to be a string or number when you ask the compiler for its type. Exchanging an XML schema or talking in a further defined language like SOAP can ensure that your program knows what the mapping should be like. that you’re using a hybrid of JSON and XML and you want to use the JSON objects to configure some class? In that case. I hope I’m wrong… Any ideas? Thanks for the great post… [ed: I tried to format your XML so that wordpress doesn’t eat it. like your colors or alphas or ratios variables. Funny. eval() is not available in AS3. Jim Kremens Says: June 11th. Thanks for the reply… “You can use code from the JSON library in Adobe Labs’ core library to do that work for you” That’s what I’m doing (with some modifications). it was easy to write a routine that would ‘actualize’ all of those strings. But now it strikes me as perhaps not the best practice. XML is used in some well-defined communication — a contract — where the parties agree on what format to speak in.

000 entry xml file in flash? Perhaps if I broke up the xml into multiple files? 15. 2007 at 1:56 pm @Alex. I’m trying to think of a clever way around it but coming up short. AS3 thinks this is trying to delete the local XMLList variable.event[n]. but. I get a run time error #1119: Delete operator is not supported with operand of type XMLList. This means that every iteration you’re going to look through the entire xml for all child nodes named “event”. 2007 at 7:19 am thank u so much.com/blog/?p=141 15/02/2008 . Is there a way to delete the results of an e4x query? 17. This function looks like a cast but is a conversion. maybe I don’t understand the plusses just yet so I won’t condemn Flash CS3 as a whole. great overview. 18. no. 2007 at 12:43 pm You say that you can delete an XML list with the delete operator but I am unable to do that in Flex Builder 2. will be evaluated in each iteration of the loop. I’m afraid you can’t filter out some nodes into an XMLList and then delete all these nodes from the source with one delete command. Just remember to minimize the work you do in each iteration. i < events. Roger Braunstein Says: June 25th. farz Says: June 26th. I’m trying to create a new XML object and what I have to create it with is a string like “Dinkie32″.time. Roger Braunstein Says: June 25th. for (var i:int = 0. i++) { var time = events[i]. 2007 at 12:59 pm Hi. 19. Alex Says: June 12th. 2007 at 1:42 pm @Rian. you should be able to create XML from a string by calling the top-level XML() function on it. Rian fowler Says: June 25th.time. 2007 at 10:49 pm Ok. Even if you stepped through all the XML nodes. Damn. im having trouble importing external XML files and setting them into a XML List Var :( http://mimswright. the expression eventXML. It’s the only access to the XML in the loop. 2007 at 2:02 pm @Nebulan. It’s definitely this statement that’s slowingdispatchEvent » AS3 E4X Rundown things down: tmpTime=eventXML. Jim 14. I’ve been struggling with generating a graph in Flash using data from an XML file. I bet you could get a serious speedup by calculating the list of possible event nodes first: var events:XMLList = eventXML.event.length(). } I bet this will run a lot faster. 20.event[n]. just remember that executing a complex string of filters can take a lot of time. Roger Braunstein Says: June 25th. Can anyone tell me how I can go about getting this done? Thanks for any help! 16. it would think you’re trying to delete the local XML variables. Nebulan Says: June 12th. Your expression is not that complex. and then find the nth. Good call. not the nodes from the original XML. this is pretty irritating.AS3 E4X Rundown | dispatchEvent Página 9 de 17 Thanks again. var xml:XML = XML("<test>testing</test>"). My problem is that I’m looping through the XML with a for-loop but anymore than 500 iterations before Flash times out. but I really do not get why I am no longer able to create an XML object by loading a string of XML.time. Is E4X less time efficient than AS2’s XML classes or is it just impossible for me to parse a 60.

while built in error reporting is better in AS3.org/XML/1998/namespace"> Attacking throw-in by <Player id="193562"> <Name>Fitz Hall</Name> </Player> <Team id="68">(Wigan)</Team> .events. I think error reporting is actually worse in AS3. [Bindable] private var dataDetails:XMLList. but it certainly is better than anything we had in AS2. in AS2 you can track down errors to the originating node or even the originating line in an XML file.w3. 26.com/blog/?p=141 15/02/2008 . You would be much better off verifying the validity of input XML in a separate environment. See http://www. I agree that E4X is not necessarily easy. Jaxim Says: http://mimswright. One node looks like this. I can’t seem to figure out a way to do this with e4X.rpc. I added a section about loading external data. </TextFeed> I would like to be able to output something like.} //script 25.AS3 E4X Rundown | dispatchEvent Página 10 de 17 21. your ability to track down problems in your XML is actually less.*.person.thanks Roger.result. I hope this helps! 23. Roger Braunstein Says: July 1st. 24. private function dataHandler(evt:ResultEvent):void {dataDetails= evt. farz Says: June 27th. hope u dont mind if i post it here.net/2006/11/xml-error-reporting-as2-trumps-as3. 2007 at 7:36 pm Hey Roger… Unlike Danny’s comment-I’ve been wrestling with a problem that I think was easier to solve in AS2-I was wondering what your take was. BenH Says: June 26th. <TextFeed id="150" correction="No" normalTime="90:00" addedTime="2:24" lang="en-GB" xmlns="http://www. 2007 at 9:58 am Great overview . like a server script. I haven’t had much experience with trying to cope with malformed XML in AS3 yet so I am inclined to believe what you say :) 27. <p>Attacking throw-in by <span class="player">Fitz Hall</span> <span class="team">(Wigan)</span>. Would really appreciate any help on that you can offer… 22. i ended up using HTTPSERVICE. 2007 at 9:43 pm Great post Roger. I think that you are right in that AS3 is very unforgiving of malformed XML. 2007 at 6:41 pm @Brian. in case someone is also looking for an alternative //script import mx. Or to be precise.webdevelopmentcentral. Roger Braunstein Says: June 26th. 2007 at 10:57 am @farz. Brian Ferris Says: June 30th. 2007 at 1:11 pm thank you very much for such a quick reply. Danny Patterson Says: June 26th.html for the gory blow-by-blow. I’m still struggling though as I’ve got some awkwardly structured XML (which I can’t change) which I’m trying to output to screen in human readable form. but in essence. Any ideas? Perhaps I’m struggling with Adobe’s implementation more than I am with e4x itself.

2007 at 12:20 pm Question: When I attempt to use the double dot syntax (”thePeople. To avoid ambiguous decisions by the compiler. Jaxim Says: July 2nd. or a type error. Jaxim Says: July 2nd. thePeople. I am still uncertain as to why using the descendant accessor causes problems in Flex.e. thePeople. 2007 at 3:47 pm @Jaxim. which is mentioned in the Flash/Flex help files. filters like (age >= 21) must apply to an existing XMLList. Brian Ferris Says: July 2nd.descendant(”*”). can you be more specific about your code and the error? Flex is fine with using the descendant accessor. Are you getting a runtime error or compile time? What error? It could be that your XML is invalid or null. thePeople. it tries to compare an XML node to an int. Hope this makes sense! 33.*.. If it helps reduce matters. 29.(age >= 21) As far as “(age >= 21)”. 31.person. Roger Braunstein Says: July 2nd. the way it’s written above. Jaxim Says: July 2nd. not all descendant nodes have children called “age” so you could have a problem with that.*.. I agree with your suggestion. or do I need to call a node name after I use the descendant accessor? i..age”) in Flex/Eclipse.” The words that are missing are “descend into nodes whose age is greater than 21.e. child() actually change the location. then you filter.(age >= 21) 32..(age >= 21) Is one way of doing what I want to do by using the “descendant” method: i. Anyone? 30. So are you saying the following line would work: thePeople. 28. but I was only using the example you had previously used in your post.(age >= 21) You’re kind of saying “descend into age greater than 21.” First you descend. Roger. 2007 at 1:53 pm @Jaxim.AS3 E4X Rundown | dispatchEvent Página 11 de 17 July 2nd. yes.com/blog/?p=141 15/02/2008 .. thePeople. let me know if the following line would work to find all the nodes (regardless where they are in the XML) that have an aka child node equal to “Rog”: http://mimswright.person.. I am attempting to do the following: thePeople. When you say thePeople. 2007 at 2:18 pm I’ve narrowed down what I’m doing wrong. They reduce the amount of matching nodes without descending into them.(age >= 21) Is this even possible. Axes like parent(). it throws an error..toString()) >= 21) This is much more precise.(age >= 21) Furthermore. 2007 at 4:48 pm Thanks. Roger Braunstein Says: July 2nd. It has to do with how I am calling the operator. and it’s also a good idea to tell the compiler how to compare that age. 2007 at 12:31 pm I just discovered that Adobe refers to the double dot syntax as “descendant accessor”. Is this syntax exclusive to Flash CS3? What is this the source of this info? I can’t find the double dot syntax mentioned anywhere in the help Flash CS3 files. Using the above example. I don’t mind AS3 being unforgiving about XML problems-I just wish it would do a better job at telling us where problems lie so we can handle unforseen conditions programmatically. or something else.(parseInt(age. 2007 at 12:22 pm Thanks anyway. let it know how to do the comparison. descendant(). However.

*. It would seem that all "item"s would require the "id" attribute for the expression to work. 2007 at 2:03 pm thanks for the article does flex or e4x provide any functions for sorting XML data. 2007 at 3:22 am Josh Tynjala has a sweet set of E4X articles: ett två tre 37.(aka == “Rog”) 34. Roger Braunstein Says: August 22nd. 38. @Jaxim. its OK! But this node not change in the “sampleData. when you click a button “MATO” . Im populating a Tree but the data needs sorting. 2007 at 6:21 pm Hi im new in E4X in ActionScript 3. please respond..xml” why??? 35.0 .com/blog/?p=141 15/02/2008 . 36. Roger Braunstein Says: August 22nd.(@id==2).45</price> </item></order> The following line would then produce an error and NOT output "fries" trace(myXML. let me use the following XML example so one of the nodes does NOT have an "id" attribute: <order> <item> <menuName>burger</menuName> <price>3. Colin Says: September 30th. You would think that since the first "item" doies not have an ID. the above trace statement would ignore the first node and find the node where (@id ==2).item.95</price> </item> <item id=’2′> <menuName>fries</menuName> <price>1. the workaround is to use attribute(”foo”) rather than @foo. make sure the expression is applicable to all of the nodes or else you will get an error. For example. Jaxim Says: July 27th. and i have one question if you could please answer me : This is my example: —————————————– ——————————————— And de XML file is: —————————————— ———————————————— My question: In RunTime this program . http://mimswright.menuName). any help would be appreciated. 2007 at 11:19 am If you use an expression to find a value. matias Says: July 10th. 2007 at 3:23 am Btw. but that’s not the case. Error produced… ReferenceError: Error #1065: Variable @id is not defined. Becasue the 1st "item" does not have an id.AS3 E4X Rundown | dispatchEvent Página 12 de 17 thePeople. If anyone knows of a workaround for this problem. the nopde month=”March” chance to month=”MATO” . it produces an error.

Says: October 17th. The most recent: http://freerpad. Small world! :) 42. I banged my head against some e4x namespace issues for about 2-3 hours (this post was very helpful). 2007 at 7:44 pm Great post Roger! I kinda wish Adobe would have switched the length property of an Array from a getter to a regular method thanks to the length function of XMLList. } return this. good info.1].elements()[this.first impressions Says: October 21st.com/blog/?p=141 15/02/2008 .com/blog/roger/as3-e4x-rundown […] 43.nextSibling = function() { if (this. } return false.elements()[this. // Implement new methods to the XML class XML. 739 Saint Louis St » Blog Archive » Rusty e4x? Good reference links to help you brush up. Jim Freer Says: October 3rd.isDocumentElement()) { return true.childIndex() .lastElement = function() { return this.length() . Donovan Adams Says: October 14th.elements()[0]. This combined with the current E4X API should pretty much fill some gap.elements(). 2007 at 11:22 pm […] I don’t understand XML namespaces at all. } XML. the bitmechanic » Blog Archive » Flex . } XML.AS3 E4X Rundown | dispatchEvent Página 13 de 17 39.parent() === undefined) { return true. } http://mimswright.prototype.isFirstElement = function():Boolean { if (this.1]. 2007 at 5:36 am I started monkey patching the XML object to have more convient functions for XML tree traversal.prototype. thanks for the link! 41.prototype. 2007 at 10:14 am […] http://www. You should consider a post on the use of XML namespace and how useful and powerful it is:) BTW. } XML. Roger Braunstein Says: October 4th.partlyhuman.elements()[this.prototype.isDocumentElement = function():Boolean { if (this. } XML.firstElement = function() { return this.parent() === undefined) { return undefined.) I also did the last year’s mini site with Moses. […] 44.blogspot.prototype.parent().prototype.childIndex() + 1]. Alexandre Conrad Says: October 26th.parent() === undefined) { return undefined.parent(). 2007 at 12:08 am @Jim. } XML.previousSibling = function() { if (this.html 40. 2007 at 9:49 pm I have several posts on sorting XML data for trees. } return this.com/2007/07/morehierarchical-sorting-e4x-xml-for. I took over J. Buzzeo’s spot over at SciFi when you did the Triangle site.

2007 at 10:25 pm Another fun tidbit about the as3 XML object: It can be used to represent graphs that go beyond simple trees. } if (this. unlike the old AS2 XML the examples are numerous. Alexandre Conrad 45.child2″.give this guy an ipod or something! 49.parent() method becomes a lot less useful. matt eisenberg Says: November 27th. Are there any tips and caveats with XMLListCollection that you or any of you know of? 46. Metal Hurlant Says: November 15th.parent(). } XML. How about XMLListCollection? I’ve managed to store HTTPService result to an XMLListCollection. } return false. 2007 at 9:15 am Wow thanks . } //////////////////////////////////////// Regards.firstElement() === this) { return true.isDocumentElement()) { return true. And lets say you have a complex string that has the e4x path you want: var path:String = “parent2. I agree that E4X looks deceptively simple.AS3 E4X Rundown | dispatchEvent Página 14 de 17 if (this. http://mimswright.lastElement() === this) { return true. He has also made the […] 48. the . 2007 at 2:18 pm In case someone else needs to do this. in many ways.isLastElement = function():Boolean { if (this. any non-cyclical graph can be represented with XML objects. David Frankson Says: November 27th.parent(). The downside is. since it will only point to the *last* parent the node was added to. 2007 at 8:23 pm […] friend Roger has written an in-depth article covering AS3 and E4X over at DispatchEvent which is quickly turning into a very lively dialogue. This should help E4X newcomers. Just like XML itself. 2007 at 4:47 am Excellent article.com/blog/?p=141 15/02/2008 .prototype. 47. I believe E4X is much simpler than the old AS2 XML implementation but what makes E4X difficult is the LACK of samples and documentation. In general. edit and send it to another HTTPService. } return false. cutting out any way to access the other parents a node may have.this is like the “missing manual” for e4x! Hey adobe . Sekati Labs » Archive » AS3 + E4X Resources Says: November 17th. Mark Serrano Says: November 13th. lets say you have some XML: var sample:XML = <root> <parent1> <child1/> </parent1> <parent2> <child2/> </parent2> </root>. In fact.

Am I the only one with this problem? Is there any solution? My ultimate goal is to get a function name or attribute from the e4x.@tid)[0]. 杜增强.) 53. The question (what is this. devon Says: November 29th. although i am not sure why e4x would make something normal into a crazy reach-around workaround… node. not just for this hack but also the official replace methods. does anyeone know the proper syntax? Anyway.descendants(path). the inline-variable syntax is only valid for XML literals (typed directly into code). It almost answered my question which took a lot of googling to find. which turns out to be absurdly complicated – or maybe noone knows the official way. (Pardon my griping but those methods are badly documented and seem relatively worthless. 52.name()] = att. 2007 at 10:13 pm @Rian et all Re: #1119: Delete operator is not supported with operand of type XMLList… I have struggled and suffered here also…best I can figure is to access elements of the dynamically created XMLList via array index.frmt. 55. path). Roger Braunstein Says: January 29th. you know that you can’t load a file like that right? You have to wait for the URLLoader to complete loading before you can access the data property. 2008 at 3:45 pm Roger. Since as3 has no eval(). 50.com/group/xpath-as3/browse_thread/thread/7929b1384b6bcc5b. try editing your comment and using the link provided above the comments. jeopardy?) was how to replace the text value of a node.google. Roger Braunstein Says: http://mimswright.xml”)).com/blog/?p=141 15/02/2008 . Claims it is malformed. ie: delete XML_nodes. for(var att:* in x.AS3 E4X Rundown | dispatchEvent Página 15 de 17 sample. this is a great post. eg: in font. Here is peter’s solution which works great. Your XML was eaten by Wordpress. If this functionality is supported. path notation even though “*” will hit all descendants. 2008 at 4:17 pm It is not accepting variables ({}) in external e4x files.html with the statement: E4XParser. I hope the above is clear. I would suggest adding a section to your post on replacing nodes and content.(@tid == e. 2007 at 9:03 pm AS3 E4X Rundown… By Roger Braunstein | on May 21.parent().term.attributes) t[att. I found a simple library that can do this: http://www.xml: in as3 file: … var x:XML = new XML(new URLLoader(new URLRequest(”font.adobe. The answer came from Peter Hall at a forum thread here: http://groups. including the Flash documentation. it doesn’t like .com/devnet/flex/articles/e4x. moses gunesch Says: January 26th. 2007… 51.data).element.childIndex()] = “blah”. Also.evaluate(sample. … var t:textFormat = newTextformat(). I thought I could pass in an attribute as a variable. will not work.children()[node.COM Says: November 27th. 2008 at 4:27 pm @Sam. Sam Goody Says: January 29th. It claims that align is malformed 54.

flash. which all executes way closer to the speed of native applications. Please use the link provided above the comments thread to encode xml for comments. indeed. compile-time errors in runtime code… 3. Furthermore. each person’s copy of Flash Player would also have to have a full compiler for AS3. Roger Braunstein Says: February 1st. you have to do that from an outside perspective. I also would be able to store the reference to a function inside the xml (func)function1(/func) which I cannot figure out any way of doing now. Andrew Says: February 5th. etc. 2008 at 12:59 am E4X: Beginner to Advanced. and more could communicate with a common tongue. You can’t just shoot at yourself. I should add that. Sam Goody Says: January 31st.Re:My last post 1) I know how to load xml. the problem you’re running into is that. it had better treat that XML just like everyone else in the world treats XML or it won’t be very good at its job. Roger Braunstein Says: January 31st. Andrew Says: February 5th. Is that becuase external e4x doesn’t handle comments.AS3 E4X Rundown | dispatchEvent Página 16 de 17 January 29th. in order to replace nodes. What would be the best approach for swapping positions of nodes in an xmllist? 60. It is much more likely to have your example file above coming from a database (created by people. just wanted the comment to be clean. 2008 at 3:24 am @Roger . there’s a very subtle difference between modifying existing nodes and replacing nodes. AS3 gets its speed from being compiled to a bytecode and then being interpreted by the AVM or even interpreted further into machine code. so I’d like to add a section on that.php) than residing in the flash file itself!! And if the abilities are going to be limited (I also had a problem with external CDATA). security sandbox. Nobody’s going to change the way XML works for E4X. 2008 at 1:49 pm @Sam: 1. This would make Flash Player much bigger to download which goes against one of Adobe’s big priorities with the Flash Player platform. Thanks for making it better with your comments! 58. yes. another great E4X article by Josh Tynjala @ Yahoo! 59. Comments in XML must be typed in <!−− this kind of tag −−> 4. 2008 at 3:06 pm http://mimswright. The {} syntax is a convenient shortcut for creating XML inline… it’s not part of XML. that kinda turns it into a vaporware. Well… XML is the interchange language. How do I post without Wordpress eating my tags? 2) XML is first and foremost an interchange language: a way that php. 3) I tried to put comments into the external URL using /* — */. The thing is. So that’s why you have that awkward syntax which jumps up and then finds its way back down. Also. If it was still there. aspx. That means for you to be able to eval() things. It balked.) 3) I guess the real gripe I have is Adobe dropping eval(). If you could add it. I would be able to evaluate the xml and get my variables and cdata. E4X is a programming tool. I think this article is already the semi-official docs . When you load in an XML file with Flash. 2.5. If you can’t use the power of e4x in external files. or are comments left with a different format? 4) Thanks for the great work 57. And to store unencoded urls. 3. having a section on replacing and modifying data. 2008 at 4:31 pm @Moses. Weird analogy. 2008 at 1:08 pm Sorry if I missed this in here if someone already pointed out a technique. you have to stand up on a ledge so you can see what you wanna shoot and then shoot. It’s a good idea. Most of the ways you modify data in E4X replacing nodes. let there be clear documentation about the limitations. eval() would bring in a lot of interesting and strange exceptions to think about in terms of application context. I did coincidentally run into some problems with CDATA.com/blog/?p=141 15/02/2008 . 56.

delete blogs. ie: var delNum:Number = blogs_cb.AS3 E4X Rundown | dispatchEvent Página 17 de 17 Well. Click on the picture to hear an audio file of the word.insertChildBefore(blogs. blogs.? 61.blog[delNum-1].blog[delNum-1].clone). http://mimswright. let us know! Leave a Reply Name (required) Mail (will not be published) (required) Website Anti-spam word: (Required)* To prove you're a person (not a spam script). blogs.com/blog/?p=141 15/02/2008 .clone). I had to use the clone to hold the node while I deleted its original before inserting. 2008 at 3:22 am Is TTS Engine(Text-To-Speech). If anyone knows of a TTS implementation. allika Says: February 7th. Submit Comment dispatchEvent is proudly powered by WordPress Entries (RSS) and Comments (RSS). delete blogs. This does not: clone = blogs. 2008 at 4:15 pm @allika TTS is NOT a built-in feature of AS3.an inbuilt feature of AS3 62. I got it to work (swapping nodes) but can anyone explain this? This works: clone = blogs. Mims Wright Says: February 8th.blog[delNum].insertChildBefore(blogs.blog[delNum]. For both the above delNum is derived from the dataProvider the XMLList generated.blog[delNum].selectedIndex Sorry if this was obvious but Deleting the node after doing a insertChildBefore was not working for me. type the security word shown in the picture.blog[delNum]. If there is a better way….