Apr
03

Parsing xml in Flex - The case of tag names with a dash

I am a fan of json.
I use it extensively but sometimes I am forced to use xml. A pretty well know way to parse xml in Flex and Adobe air is the following:

  var xml:XML = new XML("<data><tag>content</tag></data>");
  private function parse():void {
	 for each (var t:XML in xml.children()) {
		trace("tag name: "+t.name()+" tag content "+t.text());
	}
  }



Sometimes you are not the one who establishes tag names, e.g. xml comes from a webservice and you have to use it as it is. In developing Posty I had to parse xml coming from a microblogging service, Tumblr. A sample xml returned by tumblr is the following.

<post id="30451729" ...>
	  <regular-body>Text of my post...</regular-body>
</post>



Notice there is a dash in some tag name. To render data you parse the xml and extract relevant data. Adopting the same approach explained above, to retrieve the content of a tag you’d write:

  for each (var x:XML in xml.posts.post) {
    trace("my regular body is "+ x.regular-body);
  }



You will not be able to run this code. The compiler will say: access of undefined property body. What! I can’t parse xml with dashed tag names? No you can’t. More evidence from here[link]. The solution is to exploit a different syntax, which allows to access data in a dashed-name tag:

  for each (var x:XML in xml.posts.post) {
    trace("my regular body is "+ x.child("regular-body"));
  }



The compiler will be happy and your xml will be parsed successfully.

Share/Save/Bookmark

2 Comments

Comments RSS Feed  

Sorry, the comment form is closed at this time.

top