Novice Knowledge (Header Edit)

NOVICE
KNOWLEDGE

Tricks, tips, snippets, tutorials, and articles for the amateur web developer.

Thursday, June 13, 2013

AS3: Loading and Accessing XML Data

clear glowing brain
SmartNav

Understanding XML

If you did not already know, XML is an acronym for Extensible Markup Language.

Unlike HTML, XML is used mainly for storing unsecured data, like a simple list of popular movies, sports teams, or video games. Also unlike HTML, XML does not contain predefined elements with predefined styles. In XML you are allowed to define your own elements with custom styles, which is why it is referred to as an "Extensible" Markup Language.

If you are interested in learning how to save secure information via AS3; such as, login information, save game data, or personal information. Shift gears to SQLite on Database Entry.

* If you are developing Air for iOS or Air for Android applications with save data, making use of "SQLite" is a must. No exceptions!

Creating the XML File

In order to access an external XML file via AS3, you obviously need to create it first by doing the following:

  1. Toggle the file extensions on in order to display the extensions, or file types, of files on your computer.
    Ex: The ".txt" in the text document file "list.txt"
  2. Right click > New > Text Document, and name it "list.xml"
  3. When prompted, click "Yes" and you will have successfully created a basic XML file.

After creating "list.xml", double click to open it, or Right Click > Edit, and paste into it the following XML code below:



 
  Up
  Ted
  Brave
  Avatar
  Cars 2
 
 
  Oklahoma City Thunder
  Green Bay Packers
  San Antonio Spurs
  Indiana Pacers
  Memphis Grizzlies
 
 
  Pong
  Words With Friends
  Pitfall
  NBA 2K11
  Guitar Hero 2
 

 

The information within an XML document must first begin with an "XML" tag, with a version number, and which language to encode like so:


       

An external XML file must also include a tag that wraps all other tags, in this example it is the <log> tag:


 ...

  

Loading the XML File

In order to load the XML file "list.xml" into AS3, we begin by declaring an XML variable called "list" and a URLLoader variable called "xmlDataLoader":

import flash.net.URLLoader;

var list:XML;
var xmlDataLoader:URLLoader = new URLLoader();
 

Next we tell the URLLoader to load the local file "list.xml" by requesting its URL address, then add a Listener for when it is finished loading. The listener will then call a function that will process the loaded file's data. We will name this function "processXMLData":

This example XML file is in the same folder where the ".swf" file is published; therefor, a directory path is not required.

You can also access an XML file from a server by requesting its web address.


import flash.net.URLLoader;
import flash.net.URLRequest;

var list:XML;
var xmlDataLoader:URLLoader = new URLLoader();

xmlDataLoader.load(new URLRequest("list.xml"));
xmlDataLoader.addEventListener(Event.COMPLETE, processXMLData);
 

Inside the function "processXMLData" is where we set the XML variable equal to the loaded file&qpos;s data.

import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.events.Event;

var list:XML;
var xmlDataLoader:URLLoader = new URLLoader();

xmlDataLoader.load(new URLRequest("list.xml"));
xmlDataLoader.addEventListener(Event.COMPLETE, processXMLData);

function processXMLData(event:Event):void
{
 list = new XML(event.target.data);
}
 

If we trace the XML variable "list"…

import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.events.Event;

var list:XML;
var xmlDataLoader:URLLoader = new URLLoader();

xmlDataLoader.load(new URLRequest("list.xml"));
xmlDataLoader.addEventListener(Event.COMPLETE, processXMLData);

function processXMLData(event:Event):void
{
 list = new XML(event.target.data);
 trace(list);
}
 

The output should appear exactly as it does in the XML file "list.xml":


  
    Up
    Ted
    Brave
    Avatar
    Cars 2
  
  
    Oklahoma City Thunder
    Green Bay Packers
    San Antonio Spurs
    Indiana Pacers
    Memphis Grizzlies
  
  
    Pong
    Words With Friends
    Pitfall
    NBA 2K11
    Guitar Hero 2
  

  

Accessing Elements Within Your XML File

Accessing specific elements within your XML file is as simple as using dot "." notation.

function processXMLData(event:Event):void
{
 list = new XML(event.target.data);
 trace(list.category); /*Output every element within every category tag.*/
}
 

When accessing elements within an XML file, do not include the wrapper tag within the dot notation.

The following code will give an output error:

function processXMLData(event:Event):void
{
 list = new XML(event.target.data);
 trace(list.log.category); /* Improper syntax, remove "log" */
}
  

If your syntax is correct, your trace output will look almost exactly as it did before, but without the <log> tag:


  Up
  Ted
  Brave
  Avatar
  Cars 2


  Oklahoma City Thunder
  Green Bay Packers
  San Antonio Spurs
  Indiana Pacers
  Memphis Grizzlies


  Pong
  Words With Friends
  Pitfall
  NBA 2K11
  Guitar Hero 2

  

And the following code…

function processXMLData(event:Event):void
{
 list = new XML(event.target.data);
 trace(list.category.title);
}
  

Will output every <title> tag within every <category> tag in your list.

Up
Ted
Brave
Avatar
Cars 2
Oklahoma City Thunder
Green Bay Packers
San Antonio Spurs
Indiana Pacers
Memphis Grizzlies
Pong
Words With Friends
Pitfall
NBA 2K11
Guitar Hero 2
  

XML and the Index Method

You can also use dot notation in conjuction with the index method – "[i]" used to access array elements; for example:

function processXMLData(event:Event):void
{
 list = new XML(event.target.data);
 trace(list.category[0]); /*Output every element within the 1st category, not just the title elements.*/
 trace(list.category[0].title); /*Output only every <title> element within the 1st category.*/
}
 

Output of the 1st trace statement:


  Up
  Ted
  Brave
  Avatar
  Cars 2
  Example Tag

  

Output of the 2nd trace statement:


  Up
  Ted
  Brave
  Avatar
  Cars 2

  

Not specifying which category, will retrieve every element within each category…

function processXMLData(event:Event):void
{
 list = new XML(event.target.data);
 trace(list.category.title[6]); /*Gather each title within each category and output the 7th title.*/
}
 

Output:

1
Green Bay Packers

And of course specifying which category will only retrieve the elements within that category…

function processXMLData(event:Event):void
{
 list = new XML(event.target.data);
 trace(list.category[1].title[4]); /*Output the 5th title in the 2nd category.*/
}
 

Output:

1
Memphis Grizzlies

Accessing XML Attributes

To access any attribute of an element in your XML file, use the ".@" method.

function processXMLData(event:Event):void
{
 list = new XML(event.target.data);
 trace(list.category[0].@name); /*Output the name attribute of the 1st category.*/
}
 

Output:

1
Movie Titles

XML and "FOR Loops"

Instead of typing a line of code to output the data from every element in your XML file, simply make use of the "FOR Loop" statement.

Tedious, rookie syntax:

function processXMLData(event:Event):void
{
 list = new XML(event.target.data);
 trace(list.category[0].@name + ":");
 trace(list.category[0].title[0] + ",", list.category[0].title[1] + ",", list.category[0].title[2] + ",", list.category[0].title[3] + ",", list.category[0].title[4] + "\n");
 
 trace(list.category[1].@name + ":");
 trace(list.category[1].title[0] + ",", list.category[1].title[1] + ",", list.category[1].title[2] + ",", list.category[1].title[3] + ",", list.category[1].title[4] + "\n");
 
 trace(list.category[2].@name + ":");
 trace(list.category[2].title[0] + ",", list.category[2].title[1] + ",", list.category[2].title[2] + ",", list.category[2].title[3] + ",", list.category[2].title[4]);
}
 

Proper, programmer syntax:

function processXMLData(event:Event):void
{
 list = new XML(event.target.data);
 for (var i:int = 0; i < list.category.length(); i++)
 {
  var titles:String = ""
  trace(list.category[i].@name + ":");
  for (var j:int = 0; j < 5; j++)
  {
   titles += list.category[i].title[j];
   if (j == 4)
   {
    if (i != list.category.length() - 1)
    {
     titles += "\n";
    }
   }
   else
   {
    titles += ", ";
   }
  }
  trace(titles);
 }
}
 

The output for each:

Movie Titles:
Up, Ted, Brave, Avatar, Cars 2

Sports Teams:
Oklahoma City Thunder, Green Bay Packers, San Antonio Spurs, Indiana Pacers, Memphis Grizzlies

Video Games:
Pong, Words With Friends, Pitfall, NBA 2K11, Guitar Hero 2
  

You may begin to think that the rookie way is simpler and requires less code; however, when you begin to handle XML files with massive amounts of data, containing higher levels of nested elements, and multiple attributes…

The "FOR Loop" method will still remain this simple.

To access the number of occurrences of an element within an XML file, instead of an array, you must append "()" to the ".length" method.

for (var i:int = 0; i < list.category.length; i++) /*Error, improper syntax.*/
{
 ...
}
  
for (var i:int = 0; i < list.category.length(); i++) /*Correct, proper syntax.*/
{
 ...
}
  

More on FOR Loops.

In depth tutorial – SQLite on Database Entry.

In depth tutorial – Arrays & Multi-Dimensional Arrays.

Wednesday, June 12, 2013

Getting Started: The Basics

clear glowing brain
SmartNav

To consider yourself a developer, you need to learn at least HTML, CSS, a little graphic designing, and JavaScript; even more so to consider yourself a web developer. It is imperative that you learn them in that order as well – create the web document with HTML, style it all fancy with CSS and graphics, and then make the web page interactive with JavaScript.

HTML – HyperText Markup Language

Learning HTML can be pretty boring at first, because all you are doing is committing to memory all of the predefined tags and possible attributes for each.

The most often used tag is the <div> tag.

Common attributes associated with the <div> tag are shown below:

  1. The class attribute, <div class="a_class_name">
  2. This class attribute links the tag to a specific style defined in the CSS file with the label "a_class_name".

  3. The style attribute, <div style="some simple styling">
  4. You can set this attribute equal to a specified style instead of linking it to a style in a CSS file.

  5. The id attribute, <div class="an_identifier_name">
  6. This attribute can be linked to a specified style defined in the CSS file and/or allow script access to its associated tag.

With so many different tags rendering content differently and with different possible attributes, memorizing even the most common tags and their possible attributes will require significant commitment; however, without learning HTML or even XML you won't be capable of developing webpages…
Continue to » HTML Lessons

CSS – Cascading Style Sheets

Now the fun begins when learning CSS. Without proper CSS styling, and well-thought out graphics, a web page will just be an unattractive clump of data and space. CSS styling is how you "hook-up" a webpage making it more attractive to viewers.

A common style would be setting the background color of the web page either through the main HTML tag or the main BODY wrapper tag like so:

  1. html {background-color:black;}
  2. or

  3. body {background-color:black;}

The greatest feature about CSS is that developers can easily add styling to replace simple graphics or pseudo styling in the place of JavaScript, thus simplifying the design process. It also improves the overall look and feel with what I like to call dynamic simplicity…
Continue to » CSS Lessons

JavaScript – Client-Side Programming Language

After feeling confident with HTML editing and enjoying CSS styling, you will be amazed with what you can do with JavaScript.

JavaScript is a server-side language that allows real-time dynamic changes to occur on a webpage, and much more, for a plethora of unique reasons.

A few common uses of JavaScript include:

  1. Developing amazing animations.
  2. Developing a User Interface (UI) to create a fully interactive webpage.
  3. Handling cross-browser compatibility issues.

Most people, such as myself, use JavaScript as listed above to mainly develop simple web-based applications and widgets.

And after learning the basics of JavaScript, developers can learn Action Scripting for developing more powerful animations, apps, and UI's, including programming native applications for desktop/laptop computers, smartphones, and tablets…
Continue to » Javascript Lessons