Tuesday, September 14, 2010

Working with XML data using AS3: Part 5

Today we will learn about filtering your XML data.

In this tutorial, I will be using the second edition of my XML document (catalog2.xml), which has been used in the previous tutorial too. This is just a reminder, so people won't confuse this with the first version of the document, because it has different layout. In this XML file I have name and price of the product as attributes and the description between the tags.

Sometimes it is needed to only retrieve data that matches a specific criteria. For example, we might only want to show the products, that have price of $50, we might only want to show chairs, etc.

In the next example, I will get the description of product called Chair. What I need to do, is to write the path to the product node and then check if its name matches "Chair". Here:

function parseXML(xmlData:XML):void
{
trace("Parsing:");
trace("-----------------");
trace(xmlData.product.(@name=="Chair"));
}

I put the @ symbol in front of name, because it is an attribute. If you test your movie now, it will output:

XML file loaded!
Parsing:
-----------------
Something to sit on

Sometimes we might forget about case sensitivity of our product names, for example, it could've been Chair or chair or even CHAIR in the XML document. We can ignore case sensitivity by turning the text to lower case:

function parseXML(xmlData:XML):void
{
trace("Parsing:");
trace("-----------------");
trace(xmlData.product.(@name.toLowerCase()=="chair"));
}

It could be also needed to filter by multiple criterias. For example, I only want to search for chairs that are priced $50. I need to use the && operator in this case:

function parseXML(xmlData:XML):void
{
trace("Parsing:");
trace("-----------------");
trace(xmlData.product.(@name.toLowerCase()=="chair" && @price=="$50"));
}

The output window gives us the same old "Something to sit on". What if we want to search for something that is $70, but is not a chair? The != operator needs to be used instead of ==.

function parseXML(xmlData:XML):void
{
trace("Parsing:");
trace("-----------------");
trace(xmlData.product.(@name.toLowerCase()!="chair" && @price=="$70"));
}

Output:

XML file loaded!
Parsing:
-----------------
Something to put stuff on

Thanks for reading!

Related:

Working with XML data using AS3: Part 1
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 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