Adding nodes and attributes to XML using E4X

Posted by: James on Sunday, May 9th, 2010

Initially I was under assumption E4X is something very complex to work with having habituated to AS2 style and was still using XMLDocument. However gave E4x a try.. My aim is to add an attribute and a node under it. Base XML what I have is below.

1
2
3
4
5
6
7
8
9
10
var xmlData:XML = <classInfo class="XI" subject ="Maths"></classInfo>;

if(xmlData.chapter.@label =="CN1"){
    trace("label exists")
}else{
    trace("label doesn\'t exist");
    xmlData.chapter.@label = "CN1";
}

trace("xmlData  "+ xmlData.toXMLString());

trace what comes out is

1
2
3
4
label doesn't exist
xmlData  <classInfo class="XI" subject="Maths">
  <chapter label="CN1"/>
</classInfo>

Adding nodes with conditions, this really saves lot of effort and lines of code

1
2
3
4
5
6
7
8
if(xmlData.chapter.(@label =="CN1").lesson.@label == "CN1LN1"){
    trace("its there ");
}else{
    trace("oops missing");
    xmlData.chapter.(@label =="CN1").lesson.@label = "CN1LN1";
    xmlData.chapter.(@label =="CN1").lesson.(@label = "CN1LN1").appendChild("Some dummy text");
}
trace("xmlData  "+ xmlData.toXMLString());

Below is the trace result

1
2
3
4
5
6
7
oops missing
xmlData  <classInfo class="XI" subject="Maths">
  <chapter label="CN1">
    <lesson label="CN1LN1">Some dummy text</lesson>
  </chapter>
</classInfo>
xmlData  Some dummy text