Recipe 20.5. Adding Attributes to an XML Element


Problem

You want to add attributes to an XML element.

Solution

Use the @ operator in E4X syntax to assign attributes to element nodes.

Discussion

Use the @ operator to assign attributes to an element with E4X; the basic syntax looks like this:

elementNode.@attributeName = "value";

Use the dot operator (.) after an element node variable, followed by the @ operator. Immediately after the @ symbol, specify the name of the attribute, and use a regular assignment statement to give the attribute a value. The value to the right of the equals sign is converted to a string before being assigned:

// Create an XML instance to work with var example:XML = <example><someElement/></example>; // Add some attributes to the someElement element node example.someElement.@number = 12.1; example.someElement.@string = "example"; example.someElement.@boolean = true; example.someElement.@array = ["a", null, 7, undefined, "c"]; /* Displays: <example>   <someElement number="12.1" string="example" boolean="true"    array="a,,7,,c"/> </example> */ trace( example );

When using this syntax, the attribute name must be a valid variable name. This means that the attributes must have names consisting of numbers, letters, and underscores, and the first character cannot be a number. However, XML attribute names can sometimes contain other characters that, when used with the @ operator, generate compile errors. In these situations, you can use bracket notation to create attributes whose names contain invalid variable name characters. For example:

example.someElement.@["bad-variable-name"] = "yes";

You can also use bracket notation to create attributes dynamically, building the attribute name with variable values. For example:

example.someElement.@["color" + num] = "red";

See Also

Recipe 20.9




ActionScript 3. 0 Cookbook
ActionScript 3.0 Cookbook: Solutions for Flash Platform and Flex Application Developers
ISBN: 0596526954
EAN: 2147483647
Year: 2007
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net