2

Is there any way to do something like the following (pseudocode) in Flex:

var x:XML = <xml>
  if(condition){
    <tag>hello</tag>
  }
</xml>;

which would return <xml><tag>hello</tag></xml> if the condition was true and <xml></xml> (or <xml/>) if the condition was false?

ADDITIONAL NOTE: I know how to append children, etc. I am looking for a way to do this in the literal expression.

Eduardo
  • 8,362
  • 6
  • 38
  • 72

2 Answers2

6

I was really amazed at how simple it is, and at how powerful AS3 can be. The following actually worked:

var x:XML = <xml>{condition ? <tag>hello</tag> : ""}</xml>;

Eduardo
  • 8,362
  • 6
  • 38
  • 72
1

Use the appendChild method:

var sample:XML = <sample><items/></sample>;   
if( condition ) sample.items.appendChild(<tag>hello</tag>);
else sample.items.appendChild( </tag> );
ethrbunny
  • 10,379
  • 9
  • 69
  • 131
  • Thanks but I was looking for a way to do this inline in the literal. My actual XML is more complex than that (and the node where I would have to append the child would be deeper inside) – Eduardo Dec 13 '12 at 13:28
  • Hmm.. maybe with an xslt? I guess you'd have to create it externally and then import it.. but AFAIK there isn't any logic available inside an XML tag declaration. – ethrbunny Dec 13 '12 at 13:30
  • that's what I feared. I was hoping for something inside braces that would return a string and be "lifted up" as markup – Eduardo Dec 13 '12 at 13:31
  • Maybe this? http://stackoverflow.com/questions/449367/performing-xml-transformations-in-flex – ethrbunny Dec 13 '12 at 13:33
  • Ugh; kind of complex. I think I have found what I need (will post the answer) – Eduardo Dec 13 '12 at 13:38