[ Team LiB ] |
Recipe 19.6 Adding Attributes to an XML Element19.6.1 ProblemYou want to add attributes to an XML element. 19.6.2 SolutionAssign properties to the attributes property of an XMLNode object representing an element. 19.6.3 DiscussionEvery XMLNode object has a read/write attributes object that determines the attributes of the element. You can assign properties to the attributes object, and those properties are automatically added to the element's attributes. For example: my_xml = new XML( ); myElement = my_xml.createElement("myFirstElement"); // Create attributes a, b, and c for myElement. myElement.attributes.a = "eh"; myElement.attributes.b = "bee"; myElement.attributes.c = "see"; my_xml.appendChild(myElement); // Displays: <myFirstElement c="see" b="bee" a="eh" /> trace(my_xml); When you assign values to the attributes object, be careful not to overwrite the entire object, as in: myElement.attributes = {a: "eh", b: "bee", c: "see"}; Using an object literal to add multiple properties will add extra, undesired attributes since the new object also includes two hidden properties, _ _proto_ _ and constructor. Now, let's talk briefly about some of the things you can and cannot do with attributes in Flash. First of all, even though XML allows for attribute values containing newline characters, Flash does not. Therefore, if your attribute will contain a newline, be sure to use a nested node instead. Also, if you access attributes using dot syntax, as shown in the preceding example, you must use valid Flash variable names for the names of the attributes. 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 for good reasons. For example, though a full discussion of namespaces is beyond the scope of this book, XML namespaces can require that an attribute's name contain characters such as a colon (:). You can use array-access notation to create or read attributes whose names contain invalid variable name characters. For example: myElement.attributes["xmlns:soap"] = "http://schemas.xmlsoap.org/wsdl/soap"; 19.6.4 See AlsoFor more information on using attributes in XML, see Recipe 19.2 and Recipe 19.10. |
[ Team LiB ] |