Using E4X with XML in AS3
Posted by: Keith H in ActionScript 3, XML, tags: E4X Filtering, Regular Expressions, XMLThe XML examples represent a book in a library. However the book has several bookworms in it.
Using E4X we can find these bookworms.
<library> <book> <page id="one"/> <worm name="Eddy" /> <page id="two"/> <page id="three"> <worm name="Lisa"/> <worm name="Pete" /> </page> <page id="four"/> </book> </library>
There are some E4X operators and XML methods to help use do this when combined together:
.. Access all descendants of the XML object.
. Access a property of an Object or XML.
* Wildcard, match any part of the XML.
childIndex() Index number of an XML object relative to its parent node.
name() Name of the XML node.
Return a certain "worm" node at the index it belongs to from its XMLList.
Any nested "worm" node occurrence is also considered.
var doc:XML= <library> <book> <page id="one"/> <worm name="Eddy" /> <page id="two"/> <page id="three"> <worm name="Lisa"/> <worm name="Pete" /> </page> <page id="four"/> </book> </library>; //Pick the "worm" node at index 1. var data:*=doc..*.worm[1]; trace(data.toXMLString()); /*========================================= OUTPUT: <worm name="Lisa"/> //worm[1] ===========================================*/
Delete all "worm" nodes from the xml, even the nested ones.
var doc:XML= <library> <book> <page id="one"/> <worm name="Eddy" /> <page id="two"/> <page id="three"> <worm name="Lisa"/> <worm name="Pete" /> </page> <page id="four"/> </book> </library>; delete doc..*.worm; trace(doc.toXMLString()); /*========================================= OUTPUT: All "worm" nodes are deleted. <library> <book> <page id="one"/> <page id="two"/> <page id="three"/> <page id="four"/> </book> </library> ===========================================*/
Use E4X filtering with Regular Expressions.
XML methods and Regular Expressions can be used inside parentheses to accomplish E4X filtering.
doc..*.(childIndex()==0 && /library|book/i.test(name())==false)
List all nodes that belong at a given index of their XMLList.
var doc:XML= <library> <book> <page id="one"/> <worm name="Eddy" /> <page id="two"/> <page id="three"> <worm name="Lisa"/> <worm name="Pete" /> </page> <page id="four"/> </book> </library>; //---------------------------------------------------- //Get the first node of each list whose name does not //match the regular expression. //---------------------------------------------------- var data:*=doc..*.(childIndex()==0 && /library|book/i.test(name())==false); trace(data.toXMLString()); /*========================================= OUTPUT: <page id="one"/> <worm name="Lisa"/> ===========================================*/
Entries (RSS)