Az Expattech az ünnepek alatt (dec.24-jan.1.) zárva tart. Nyitás: 2024.január 2

ExpatTech Techblog

Peter Todd 2010.10.28. 14:25

Flash Cookbook - CSS - CSS parser, parsing CSS StyleSheet and Style

Even though Flash has a built-in css parser, still it's not the best one. After running some tests it came out, it does not really support a lot of things. For example you can't use hyphen in declarations, nor you can use spaces in selectors.

These things are needed for our work, therefore the only way left is to write our own parser. In this post we write the basics - think it through, take it further and you will get a nice and handy class for your own.

Plus, the StyleSheet.parseCSS() method does not support styles not surrounded by curly brackets. This is what you can use in the attributes of an xml-tag: style="font-size: 15px". This wouldn't be understood by the built-in parser.

The basics

Syntax (http://www.w3schools.com/Css/css_syntax.asp)
 

It contains a selector and some declarations between curly brackets.

format { size: 15px; }

What we can see here is we have the selector and the decalrations (separated by a semicolon).

We have to group the string into the selector and declarations. This can be done in two steps easily with String's split function: split it by the curly brackets, then by the colon-semicolon pairs.

Flash's String.split() function works perfectly with regex(p) values too. So:

var str:String = "format{size:15px;color:#ff0000;}";
var split_str:Array = str.split(/{|}/g);
var split_format:Array = array[1].split(/:|;/g);

for(var i:int = 0; i < temp.length - 1; i += 2)
{
    trace(temp[i], ":", temp[i+1]);
}

//outputs:
//size : 15px
//color : #ff0000

 

This way you can start to parse a css string.