Using XML and ActionScript with Flex Applications - Writing to and Editing XML Objects
(Page 3 of 5 )
You can also write to and edit XML objects using ActionScript. There are three things you can do in this category:
- Modify existing data.
- Add new data.
- Remove existing data.
Using XML
You can modify existing data using the same E4X syntax you use to read the data on the left side of an assignment statement. For example, the following changes thetitleof the firstbook:
xml.book[0].title = "Programming Flex 2: Edition 1";
The following example changes the name of the secondauthorof thefirstbook:
xml.book[0].authors.author[1].@first = "Joseph";
If you want to add new data, you can use theappendChild(),prependChild(),insertChildBefore(), andinsertChildAfter()methods. Each method inserts a new XML node into anXMLorXMLListstructure. TheappendChild()andprependChild()methods each accept one parameter and insert the node at the end and at the beginning of the structure, respectively. The following adds a new publisher node to each book:
xml.book[0].appendChild(<publisher>O'Reilly</publisher>);
xml.book[1].appendChild(<publisher>O'Reilly</publisher>);
You can use theinsertChildBefore()andinsertChildAfter()methods to add a new node before or after an existing node. The methods each require two parameters: the new node to add, and a reference to the existing node. The following adds a new publication date node (publicationDate) between the authors and publisher nodes of the books:
xml.book[0].insertChildAfter(xml.book[0].authors, <publicationDate>2006</
publicationDate>);
xml.book[1].insertChildAfter(xml.book[1].authors, <publicationDate>2006</
publicationDate>);
You can remove elements using thedeleteoperator. The following example first adds a new middle attribute to an author node and then removes it:
xml.book[0].authors.author[1] = <author first="Joey" middle="Persnippity" last="Lott"
/>;
trace(xml.book[0].authors);
delete xml.book[0].authors.author[1].@middle;
trace(xml.book[0].authors);
Next: Reflection >>
More Flash Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of the book Programming Flex 2, written by Chafic Kazoun and Joey Lott (O'Reilly, 2007; ISBN: 059652689X). Check it out today at your favorite bookstore. Buy this book now.
|
|