Friday, September 10, 2010

Working with XML data using AS3: Part 1

Today we will learn why and when should we use XML wtih Actionscript 3. To start things off, we will create some simple XML files.

XML files are often used as dynamic data containers, that can be changed by the admin or (with use of additional scripts) by the users of a web-site. The idea is simple - we store some information in an XML file and then use it with another script (we will use AS3).

For example, an online shop has a catalog that is updated often. Information about each product is minimal - name, description and price. We can create an XML file to store all the products' information, to parse it with AS3 later and display a working list to the customer.

First of all, let's create an XML file. You can do that with any text editor, I prefer notepad. If you had any experience with HTML before, XML will look familiar to you, because HTML is actually based off XML. There are tags, and you are allowed to call your tags whatever you want. If you create a tag (ex. <myTag>), you must close it (</myTag>). Here is an example of a simple XML file, containg information about 3 product:

<Catalog>
<product>Chair</product>
<product>Sofa</product>
<product>Table</product>
</Catalog>

As you can see, we have 1 main block called Catalog with 3 sub-blocks called products. You can save your file now with an .xml extension (ex. myFile.xml), and it will be an XML file.

We have product names, but what if we want to store more information? We can add more tags:

<product>
<name>Chair</name>
<description>Something to sit on</description>
<price>$50</price>
</product>

However, there is another way. We can pass information as attributes to a block.

<product name="Chair" description="Something to sit on" price="$50"></product>

Another thing to note, is that if our block contains nothing between the opening and closing tags, we can close it in the first tag piece:

<myTag />

The code above equals this:

<myTag></myTag>

So we can now shorten our product tag using this method.

<product name="Chair" description="Something to sit on" price="$50" />

We can also combine attributes with the 'normal' way of using tags. For example, some might find this piece more simple to use:

<product name="Chair" price="$50">
Something to sit on
</product>

These are the basics of creating simple XML files to store information like this. More AS3-XML tutorials are coming up. Thanks for reading!

Related:

Working with XML data using AS3: Part 2
Working with XML data using AS3: Part 3
Working with XML data using AS3: Part 4
Working with XML data using AS3: Part 5
Working with XML data using AS3: Part 6
Working with XML data using AS3: Part 7
Working with XML data using AS3: Part 8
Working with XML data using AS3: Part 9
Working with XML data using AS3: Part 10

No comments:

Post a Comment