helpdesk
helpdesk

Reputation: 2074

Deleting a particular node using the e4x syntax

I have this XML structure:

<numb>
  <variable>
   <name>john</name>
   <age>12</age>
 </variable>
 <variable>
   <name>janet</name>
   <age>10</age>
 </variable>
 <variable>
   <name>johanna</name>
   <age>22</age>
 </variable>
 <variable>
  <name>harry</name>
  <age>24</age>
 </variable>
</numb>

If I try to delete the variable with name johanna I do this:

  delete numb.variable.(name=="johanna);

but then, I get this error:

 "Error #1119: Delete operator is not supported with operand of type XMLList"

suggesting the numb.variable.(name=="johanna") is an XMLList ..but then I tried this:

delete XML(numb.variable.(numb=="johanna"); 

but that didn't delete anything..

Anyone knows how I could delete a certain variable in the numb XML?

Upvotes: 3

Views: 3312

Answers (2)

kpi10
kpi10

Reputation: 21

numb.variable.(name=="johanna") 

return an xmllist of one xml element, so to delete it you have to use this syntax

delete numb.variable.(name=="johanna)[0] as XML;

Upvotes: 2

George Profenza
George Profenza

Reputation: 51837

You can retrieve the child nodes that have a different name from johanna and set those as the children nodes, using the setChildren() method.

e.g.

var xml:XML = <numb>
  <variable>
   <name>john</name>
   <age>12</age>
 </variable>
 <variable>
   <name>janet</name>
   <age>10</age>
 </variable>
 <variable>
   <name>johanna</name>
   <age>22</age>
 </variable>
 <variable>
  <name>harry</name>
  <age>24</age>
 </variable>
</numb>

xml.setChildren(xml.variable.(name != 'johanna'));
trace(xml);
/*
Outputs:
<numb>
  <variable>
    <name>john</name>
    <age>12</age>
  </variable>
  <variable>
    <name>janet</name>
    <age>10</age>
  </variable>
  <variable>
    <name>harry</name>
    <age>24</age>
  </variable>
</numb>
*/

Another option is to loop through each node that satisfies the condition and delete the corresponding node through array access notation using the childIndex() method:

short version:

for each (var match:XML in xml.variable.(name == 'johanna')) delete xml.variable[match.childIndex()];

longer version:

var xml:XML = <numb>
  <variable>
   <name>john</name>
   <age>12</age>
 </variable>
 <variable>
   <name>janet</name>
   <age>10</age>
 </variable>
 <variable>
   <name>johanna</name>
   <age>22</age>
 </variable>
 <variable>
  <name>harry</name>
  <age>24</age>
 </variable>
</numb>;

var matches:XMLList = xml.variable.(name == 'johanna');
for each (var match:XML in matches) delete xml.variable[match.childIndex()];

Upvotes: 2

Related Questions