Thursday, September 16, 2010

Working with XML data using AS3: Part 7

In this tutorial we will learn how to delete data from the XML Object.

In the previous tutorial, we've discussed how to overwrite an existing product, but sometimes we might just want to get rid of it, or a specific attribute or tag.

There is a special operator for this - delete.

Here is what our XML Object looks like right now, without any changes made:

XML file loaded!
Parsing:
-----------------
<catalog>
  <product name="Chair" price="$50">Something to sit on</product>
  <product name="Sofa" price="$100">Something soft to sit on</product>
  <product name="Table" price="$70">Something to put stuff on</product>
</catalog>

In this example, we remove the second product:

function parseXML(xmlData:XML):void
{
trace("Parsing:");
trace("-----------------");
delete xmlData.product[1];
trace(xmlData);
}

And the results:

XML file loaded!
Parsing:
-----------------
<catalog>
  <product name="Chair" price="$50">Something to sit on</product>
  <product name="Table" price="$70">Something to put stuff on</product>
</catalog>

As you can see, it is gone! Now, we might also want to remove an attribute.

function parseXML(xmlData:XML):void
{
trace("Parsing:");
trace("-----------------");
delete xmlData.product[1].@price;
trace(xmlData);
}

Output window:

XML file loaded!
Parsing:
-----------------
<catalog>
  <product name="Chair" price="$50">Something to sit on</product>
  <product name="Sofa">Something soft to sit on</product>
  <product name="Table" price="$70">Something to put stuff on</product>
</catalog>

We can remove all the products too.

function parseXML(xmlData:XML):void
{
trace("Parsing:");
trace("-----------------");
delete xmlData.product;
trace(xmlData);
}

And the results:

XML file loaded!
Parsing:
-----------------

Empty. We have removed all the tags inside our nod, so the XML object is now blank. Note, that if we try to remove xmlData, we will receive an error, saying that only dynamically defined properties can be deleted.

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