Tuesday, September 18, 2007

Working With Data in Flex: E4X

When using E4X notation, root node is not used in statements.

E4X makes dealing with AS XML objects much easier and flexible. Eliminates the need to build complicated for loops to obtain data. Was not there before 3.0.

Let us see some key E4X operators

dot [.] operator allows to navigate to a particular node type. Eg:
for XML:
private var myXML:XML = new XML();
myXML=
<parent>
   <family>
      <child age="2" weight="10">
         <name>child1</name>
         <id>0</id>
      </child>
       <child age="2" weight="15">
         <name>child2</name>
         <id>1</id>
       </child>
   </family>
   <family>
      <child age="4" weight="17">
          <name>child3</name>
         <id>2</id>
       </child>
      <child age="5" weight="20">
          <name>child4</name>
         <id>3</id>
      </child>
    </family>
</parent>

now,
myXML.family.child.name
would give
<name>child1</name>
<name>child2</name>
<name>child3</name>
<name>child4</name>

parantheses [()] operator allows to get node using condition
eg:
myXML.family.child.(name="child1")
will give
<child age="2" weight="10">
    <name>child1</name>
    <id>0</id>
</child>

attribute [@] operator can be used to do the same thing using an attribute
eg:
myXML.family.child.(@age="2")
will give
<child age="2" weight="10">
    <name>child1</name>
    <id>0</id>
</child>
<child age="2" weight="15">
    <name>child2</name>
    <id>1</id>
</child>
All the nodes matching the criteria are returned

descendant accessor [..] operator allows getting any descendant, no matter how deep they are buried.
myXML..name
will give
<name>child1</name>
<name>child2</name>
<name>child3</name>
<name>child4</name>

When we want E4X format we specify resultFormat in HTTPService:
<mx:HTTPService id="serviceId" url="http://www.myUrl.com/myXml.xml" result="handlingFunc(event)" resultFormat="e4x"/>

Questions:
  1. What is the advantage of using E4X?
  2. In E4X explain the usage of dot [.] operator.
  3. In E4X explain the usage of attribute [@] operator.
  4. In E4X explain the usage of parentheses [()] operator.
  5. In E4X explain the usage of descendant accessor [..] operator.
  6. How will HTTPService know that the format of result returned?

1 comment:

Mark said...

myXML.family.child.(@age="2")

That will change the age of all child nodes to 2. And then gives you all child nodes.

What you probably wanted to do:
myXML.family.child.(@age=="2")