XML: Apending Children

Imagine the following XML:
<list>
<item> </item>
<item> </item>
</list>
Now in ActionScript, if I loop through all children and
attempt to add text nodes to each individual node like so
(pseudocode)
children = xml.children();
for (i = 0; i < children.length(); ++i)
children
.appendChild("test" + i);
What happens here is both nodes get updated twice. It looks
like the XML code appends the child to all nodes with the same
name. So now my XML looks like this:
<list>
<item>test1 test2</item>
<item>test1 test2</item>
</list>
What I'm looking to do is this:
<list>
<item>test1</item>
<item>test2</item>
</list>
Can this be done or is the XML code in ActionScript
borked?

Hmm, I see now that rather than manage multiple xml nodes,
flex prefers to group similar nodes into a single array.I'm not
particularly fond of this as it goes against how I work with XML in
other languages and platforms, but I can live with it for now.
As a workaround, I'm removing duplicate nodes and instead
appending children to the same children over and over again. So the
result now looks like this:
<list>
<item>
item1
item2
item3
</item>
</list>
In action script, I have to do the following to access those
text nodes:
list.item.getChildren()[index];
I guess this isn't to bad. Had it worked my way, the only
difference would have been:
list.item[index]
So there's an extra step involved. Perhaps I'll just write a
wrapper that will do this for me.
If anyone wants to share their comments on this, please do.
Meanwhile I'm going to label this topic answered.

Similar Messages

  • XML has Children [wether it has or not]

    Hello Guys
    <person name="Roshi">
              <children>
                   <person name="Roomi">
                        <children>
                             <person name="Andy"/>
                             <person name="Johny"/>
                        </children>
                   </person>
                   <person name="Hazy"/>
                   <person name="sunny"/>
              </children>
         </person>;
    When i use following code
    if(xml.child("children")){  
    trace("it has children");
    }else{
    trace("it has not");
    but even it print "it has children" for Hazy and Sunny who dont have children
    I actually want to make a comparision like
    Roshi has Children
    Roomi Has children
    Andy Has not Children etc
    for each in loops works good, but i just need to make comparision
    Please guide
    Thanks in advance

    This should help I hope:
    //use a wrapper tag to provide access to the top leve person tag
    var xml:XML =<wrapper>
              <person name="Roshi">
              <children>
               <person name="Roomi">
                 <children>
                <person name="Andy"/>
                <person name="Johny"/>
                 </children>
                </person>
                 <person name="Hazy"/>
                 <person name="sunny"/>
              </children>
         </person>
          </wrapper>;
    //try not to use XMLLists as Boolean values, because they are not 'null' and therefore evaluate to true:
    if (xml.children.person.(@name=="Roomi")) trace('found Roomi, Great! (or did I?)')
    if (xml.children.person.(@name=="Room")) trace('found Room, Great! (or did I?)')
    //oh I see, so the XMLList evaluated as a Boolean is wrong...I need to check its length!!!!
    if (xml.children.person.(@name=="Roomi").length()) trace('found Roomi, Great! Now I\'m certain')
    if (xml.children.person.(@name=="Room").length()) trace('found Room wasn\'t there because the XMLList length is zero, Great! this is correct!')
    //now after I understand that, lets try the looping
    //get a person list from anywhere in the xml
    var myPeople:XMLList = xml..person;
    for each(var individual:XML in myPeople){
         var theseChildren:XMLList=individual.children.person;
         var numChild:uint = theseChildren.length()
         trace(individual.@name+" has children ?:"+Boolean(numChild))
         if (numChild) {
              trace ('the '+((numChild>1)? 'children are ':'child is '));
              for each(var directChild:XML in theseChildren) trace([email protected]())

  • How to access XML elements by name in Extendscript??

    I'm almost done the script that I've been working on, but something has been nagging me since I started. When I did start, I looked at the JS Tools Guide CS5 that comes with the extendscript ide to check how to access XML elements, children, attributes etc. It says this:
    The XML object represents an XML element node in an XML tree. The topmost XML object for an XML file
    represents the root node. It acts as a list, which contains additional XML objects for each element. These in
    turn contain XML objects for their own member elements, and so on.
    The child elements of an element tree are available as properties of the XML object for the parent. The
    name of the property corresponds to the name of the element. Each property contains an array of XML
    objects, each of which represents one element of the named type.
    So basically it converts the XML into JSON. And you can access the properties like so:
    <book category="COOKING">
         <title lang="en">The Boston Cooking-School Cookbook</title>
         <author>Fannie Merrit Farmer</author>
         <year>1896</year>
         <price>49.99</price>
    </book>
    The Javascript statement bookstoreXML.book; returns the entire list of books.
    The statement bookstoreXML.book[0]; returns the XML object for the first book.
    The statement bookstoreXML.book[0].author; returns all authors of the first book.
    A couple pages down it talks about Retrieving contained elements using children(), elements(), descendants().
    So now I look through the XML Object properties and I see that I can use:
    xmlObj.child (which) which A String, the element name, or a Number, a 0-based index into this node’s child array.
    or
    xmlObj.descendants ([name])
    name Optional. A String, the element name to match. If not provided, matches all
    elements.
    or
    xmlObj.elements (name);
    name Optional. A String, the element name to match. If not provided, matches all
    elements.
    This is an excerpt of an XML I was working with:
    <ROW xmlns="http://www.filemaker.com/fmpdsoresult"
         MODID="16"
         RECORDID="11128">
       <Sign_Type>251.dr</Sign_Type>
       <fm:Location xmlns:fm="http://www.filemaker.com/fmpdsoresult" xmlns="">5-5024</fm:Location>
       <Line1>Zone
    Floor
    3
    Patient Rooms
    R532 - R436 even
    Patient Rooms
    R522 - R446 even
    Xavier Elevators
    Zone
    Patient Rooms
    R537 - 5757 odd
    Main Elevators
    Zone</Line1>
    </ROW>
    Extendscript will not give me an anything when I try to access elements by name. Instead I have to access by index, which works, but I'd rather search for names!
    Actually the console log returns: <![CDATA[]]>
    What am I doing wrong!?

    First, those E4X XML objects are definitely no JSON (plain data) - they have a multitude of methods, even for tasks that would easily be implemented as property (e.g. the length() function), and they also bind xml element and attribute names onto the objects, allowing to target a multitude of XML nodes with a single statement. Or did you mean your script with that "it"?
    Anyway, as you found out the ExtendScript XML object handles namespaces mostly by hiding them from you.
    You could play around with global namespace settings, see the JavaScript tools guide.
    You could also explicitly specify a namespace. This works for me:
    $.writeln(myXML["fm:Location"]);
    For simple use I had most success with a brute force approach that just strips the namespaces.
    function removeAllNamespace(xml)
              var ns =new Namespace();
              var d=xml.descendants();
              for (var i=0;i<d.length();i++)
        d[i].setNamespace(ns);

  • How to add multiple skin states to SkinnableContainerSkin so that can switch among states

    Hi All,
    I have a xml which represents 2 views of SkinnableContainer, xml being parsed and converted to ui elements and stored into 2 array variables based on display property of the tag
    initially adding 1 set of array element to Container
    whenever a button clicked to show different set of array elements, calling removeAllElements() and adding different set of elements from 2nd array
    Can somebody help me converting this application to utilize "Skin States"  feature
    Sorry, Could not find way to attach demo project, copied code bellow
    Thanks in advance...
    /src/ContainerDemo.mxml
         /com.containerdemo.controls
              ButtonControl.as
              ContainerControl.mxml
              CustomContainer.as
              CustomControls.mxml
              IControl.as
              ParentControl.mxml
         /com.containerdemo.skins
              ButtonControlSkin.mxml
              CustomContainerSkin.mxml
         /com.containerdemo.utils
              XmlUtil.as
    ContainerDemo.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                                     xmlns:s="library://ns.adobe.com/flex/spark"
                                     xmlns:mx="library://ns.adobe.com/flex/mx"
                                     minWidth="700" minHeight="500"
                                     xmlns:controls="com.containerdemo.controls.*">
              <s:VGroup paddingBottom="20" paddingLeft="20"
                                    paddingRight="20" paddingTop="20" gap="20"
                                    horizontalCenter="0">
                        <s:Label text="Flex states demo" fontSize="30"/>
                        <controls:ParentControl id="pc" />
              </s:VGroup>
    </s:Application>
    XmlUtil.as
    package com.containerdemo.utils {
              import com.containerdemo.controls.ButtonControl;
              import com.containerdemo.controls.ContainerControl;
              import com.containerdemo.controls.CustomContainer;
              import com.containerdemo.controls.IControl;
              public class XmlUtil {
                        public static var ELEMENTS:Object = {
                                  "buttonElement": ButtonControl,
                                  "containerElement": ContainerControl
                        public static function parse(xml:XML):IControl {
                                  var name:String = xml.name();
                                  var clazz:Class = ELEMENTS[name];  
                                  var elem:IControl = new clazz();
                                  elem.parse(xml);
                                  return elem;
    CustomContainerSkin.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <s:SparkSkin xmlns:fx="http://ns.adobe.com/mxml/2009"
                                   xmlns:s="library://ns.adobe.com/flex/spark"                               
                                   xmlns:mx="library://ns.adobe.com/flex/mx">
              <fx:Metadata>
                        [HostComponent("com.containerdemo.controls.CustomContainer")]
              </fx:Metadata>
        <s:states>
            <s:State name="normal" />
            <s:State name="disabled" />
        </s:states>
              <s:Group id="rectGroup">
                        <s:Rect left="0" right="0" top="0" bottom="0" radiusX="8" radiusY="8">
                                  <s:stroke>
                                            <s:SolidColorStroke weight="2" color="#FF0000" alpha="0.8" />
                                  </s:stroke>
                        </s:Rect>
                        <s:HGroup top="10" left="10" right="10" gap="4">
                                  <s:Label id="containerLabel" text="{this.hostComponent.label}" />
                                  <s:Button id="compOrExpButton" label="{this.hostComponent.btnLabel}" />
                                  <mx:Spacer width="100%" />
                        </s:HGroup>
                        <s:Group id="contentGroup" left="16" right="16" top="32" bottom="32" />
              </s:Group>
    </s:SparkSkin>
    ButtonControlSkin.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <s:SparkSkin xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark"
                 xmlns:fb="http://ns.adobe.com/flashbuilder/2009"
                                   minWidth="21" minHeight="21" alpha.disabled="0.5">
              <fx:Metadata>
                        [HostComponent("com.containerdemo.controls.ButtonControl")]
              </fx:Metadata>
        <s:states>
            <s:State name="up" />
            <s:State name="over" />
            <s:State name="down" />
            <s:State name="disabled" />
        </s:states>
              <s:Label id="labelDisplay"
                 textAlign="center"
                 verticalAlign="middle"
                 maxDisplayedLines="1" minWidth="20"
                 horizontalCenter="0" verticalCenter="1"
                 left="10" right="10" top="2" bottom="2">
        </s:Label>
    </s:SparkSkin>
    ParentControl.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
                         xmlns:s="library://ns.adobe.com/flex/spark"
                         xmlns:mx="library://ns.adobe.com/flex/mx"
                         xmlns:controls="com.containerdemo.controls.*"
                         creationComplete="group1_creationCompleteHandler(event)">
              <fx:Declarations>
                        <fx:XML id="compXml" xmlns="">
                                  <elems>
                                            <buttonElement id="b1" label="Element1" />
                                            <containerElement id="c2" label="Container2" display="comp">
                                                      <comp>
                                                                <buttonElement id="c2b1" label="Element5 (Comp)" />
                                                                <buttonElement id="c2b2" label="Element6 (Comp)" />
                                                                <containerElement id="c2c1" label="Container c2c1" display="comp">
                                                                          <comp>
                                                                                    <buttonElement id="c2c1b1" label="Element c2c1b1 (Comp)" />
                                                                                    <buttonElement id="c2c1b2" label="Element c2c1b2 (Comp)" />
                                                                          </comp>
                                                                </containerElement>
                                                                <containerElement id="c2c2" label="Container c2c2" display="comp">
                                                                          <comp>
                                                                                    <buttonElement id="c2c2b1" label="Element c2c2b1 (Comp)" />
                                                                                    <buttonElement id="c2c2b2" label="Element c2c2b2 (Comp)" />
                                                                          </comp>
                                                                </containerElement>
                                                      </comp>
                                            </containerElement>
                                            <buttonElement id="b3" label="Element7" />
                                  </elems>
                        </fx:XML>
                        <fx:XML id="expXml" xmlns="">
                                  <elems>
                                            <buttonElement id="b1" label="Element1" />
                                            <containerElement id="c2" label="Container2" display="exp">
                                                      <comp>
                                                                <buttonElement id="c2b2" label="Element5 (Comp)" />
                                                                <buttonElement id="c2b2" label="Element6 (Comp)" />
                                                                <containerElement id="c2c1" label="Container c2c1" display="exp">
                                                                          <comp>
                                                                                    <buttonElement id="c2c1b1" label="Element c2c1b1 (Comp)" />
                                                                                    <buttonElement id="c2c1b2" label="Element c2c1b2 (Comp)" />
                                                                          </comp>
                                                                          <exp>
                                                                                    <buttonElement id="c2c1b3" label="Element c2c1b3 (Exp)" />
                                                                                    <buttonElement id="c2c1b4" label="Element c2c1b4 (Exp)" />
                                                                          </exp>
                                                                </containerElement>
                                                                <containerElement id="c2c2" label="Container c2c2" display="comp">
                                                                          <comp>
                                                                                    <buttonElement id="c2c2b1" label="Element c2c2b1 (Comp)" />
                                                                                    <buttonElement id="c2c2b2" label="Element c2c2b2 (Comp)" />
                                                                          </comp>
                                                                          <exp>
                                                                                    <buttonElement id="c2c2b3" label="Element c2c2b3 (Exp)" />
                                                                                    <buttonElement id="c2c2b4" label="Element c2c2b4 (Exp)" />
                                                                          </exp>
                                                                </containerElement>
                                                      </comp>
                                                      <exp>
                                                                <containerElement id="c4" label="Container4" display="comp">
                                                                          <comp>
                                                                                    <buttonElement id="c4b1" label="Element 555(Comp)" />
                                                                                    <buttonElement id="c4b2" label="Element 655 (Comp)" />
                                                                          </comp>
                                                                          <exp>
                                                                                    <buttonElement id="c4b3" label="Element 335 (Exp)" />
                                                                                    <buttonElement id="c4b4" label="Element 126 (Exp)" />
                                                                          </exp>
                                                                </containerElement>
                                                      </exp>
                                            </containerElement>
                                            <buttonElement id="b3" label="Element7" />
                                  </elems>
                        </fx:XML>
              </fx:Declarations>
              <fx:Script>
                        <![CDATA[
                                  import mx.events.FlexEvent;
                                  protected function group1_creationCompleteHandler(event:FlexEvent):void {
                                            this.customControls.parse(compXml);
                        ]]>
              </fx:Script>
              <controls:CustomControls id="customControls" />
    </s:Group>
    IControl.as
    package com.containerdemo.controls
              import mx.core.IVisualElement;
              public interface IControl extends IVisualElement {
                        function parse(xml:XML):void;
    CustomControls.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
                         xmlns:s="library://ns.adobe.com/flex/spark"
                         xmlns:mx="library://ns.adobe.com/flex/mx"
                         implements="com.containerdemo.controls.IControl">
              <fx:Script>
                        <![CDATA[
                                  import com.containerdemo.utils.XmlUtil;
                                  public function parse(xml:XML):void {
                                            for each (var child:XML in xml.children()) {
                                                      var e:IControl = XmlUtil.parse(child);
                                                      this.addElement(e);
                        ]]>
              </fx:Script>
              <s:layout>
                        <s:HorizontalLayout verticalAlign="middle" gap="15"
                                                                          paddingLeft="16" paddingRight="16"
                                                                          paddingTop="16" paddingBottom="16" />
              </s:layout>
    </s:Group>
    CustomContainer.as
    package com.containerdemo.controls
              import com.containerdemo.skins.CustomContainerSkin;
              import com.containerdemo.utils.XmlUtil;
              import flash.events.MouseEvent;
              import mx.collections.ArrayCollection;
              import spark.components.Button;
              import spark.components.Group;
              import spark.components.SkinnableContainer;
              public class CustomContainer extends SkinnableContainer implements IControl {
                        [SkinPart(required="true")]
                        public var compOrExpButton:Button;
                        [SkinPart(required="true")]
                        public var rectGroup:Group;
                        private var dispState:String;
                        private var _label:String;
                        private var _cid:String;
                        private var compControls:ArrayCollection;
                        private var expControls:ArrayCollection;
                        public function CustomContainer() {
                                  this.setStyle("skinClass", Class(CustomContainerSkin));
                        public function parse(xml:XML):void {
                                  this.compControls = null;
                                  this.expControls = null;
                                  compControls = new ArrayCollection;
                                  expControls = new ArrayCollection;
                                  this.dispState = xml.@display;
                                  this.label = xml.@label;
                                  this.cid = xml.@id;
                                  for each (var child:XML in xml.comp.children()) {
                                            var e:IControl = XmlUtil.parse(child);
                                            this.compControls.addItem(e);
                                            //trace((e is ButtonControl).label);
                                  for each (var child1:XML in xml.exp.children()) {
                                            var e1:IControl = XmlUtil.parse(child1);
                                            this.expControls.addItem(e1);
                                            //trace((e1 as ButtonControl).label);
                                  showControls();
                        [Bindable]
                        public function set cid(value:String):void {
                                  this._cid = value;
                        public function get cid():String {
                                  return this._cid;
                        public function showControls():void {
                                  if (this.dispState == "comp") {
                                            showCompControls();
                                  } else {
                                            showExpControls();
                        public function showCompControls():void {
                                  if (this.numElements >0)
                                            this.removeAllElements();
                                  for each (var e:IControl in compControls) {
                                            this.addElement(e);
                                  this.btnLabel = "Exp";
                                  this.invalidateSkinState();
                        public function showExpControls():void {
                                  if (this.numElements >0)
                                            this.removeAllElements();
                                  for each (var e:IControl in expControls) {
                                            this.addElement(e);
                                  this.btnLabel = "Comp";
                                  this.invalidateSkinState();
                        public function get ownerContainer():CustomContainer {
                                  return this.owner as CustomContainer;
                        public var b:Boolean = true;
                        public function displayCompOrExpControls(event:MouseEvent):void {
                                  if (this.btnLabel == "Exp") {
                                            if (b) {
                                                      this.reParse();
                                                      b = false;
                                            } else {
                                                      this.showExpControls();
                                  } else {
                                            this.showCompControls();
                        public function reParse():void {
                                  /*if (this.owner && (this.owner is CustomContainer))
                                            (this.owner as CustomContainer).reParse();
                                  else {*/
                                            var xml:XML = this.parentApplication.pc.expXml;
                                            var expXml:XMLList = xml.descendants().(attribute("id") == this.cid);
                                            this.parse(expXml[0]);
                        private var _btnLabel:String;
                        public function get btnLabel():String {
                                  return this._btnLabel;
                        [Bindable]
                        public function set btnLabel(value:String):void {
                                  this._btnLabel = value;
                        public function get label():String {
                                  return this._label;
                        [Bindable]
                        public function set label(value:String):void {
                                  this._label = value;
                        override protected function partAdded(partName:String, instance:Object):void {
                                  super.partAdded(partName, instance);
                                  if (instance == this.compOrExpButton)
                                            this.compOrExpButton.addEventListener(MouseEvent.CLICK, displayCompOrExpControls, false, 0, true);
                        override protected function partRemoved(partName:String, instance:Object):void {
                                  super.partRemoved(partName, instance);
                                  if (instance == compOrExpButton)
                                            this.compOrExpButton.removeEventListener(MouseEvent.CLICK, displayCompOrExpControls, false);
    ContainerControl.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <controls:CustomContainer xmlns:fx="http://ns.adobe.com/mxml/2009"
                                                                  xmlns:s="library://ns.adobe.com/flex/spark"
                                                                  xmlns:mx="library://ns.adobe.com/flex/mx"                                                              
                                                                  xmlns:controls="com.containerdemo.controls.*">
              <controls:layout>
                        <s:HorizontalLayout gap="20"
                                                                          paddingLeft="16" paddingRight="16"
                                                                          paddingBottom="16" paddingTop="16" />
              </controls:layout>
    </controls:CustomContainer>
    ButtonControl.as
    package com.containerdemo.controls
              import com.containerdemo.skins.ButtonControlSkin;
              import spark.components.Button;
              public class ButtonControl extends Button implements IControl {
                        public function ButtonControl() {
                                  this.setStyle("skinClass", Class(ButtonControlSkin));
                        public function parse(xml:XML):void {
                                  this.label = xml.@label;

    Could somebody help me?

  • Sorting XMLListCollection by nested elements

    I've been sorting XML files using an XMLListCollection when I have an XML with the following structure:
    <products>
         <product id="1">
              <field1>value</field1>
              <field2>value</field2>
              <field3>value</field3>
         </product>
         <product id="2">
              <field1>value</field1>
              <field2>value</field2>
              <field3>value</field3>
         </product>
    </products>
    by using an XMLListCollection as follows:
    var mySort:sort = new Sort();
    var xlcProducts:XMLListCollection = new XMLListCollection();
    mySort.fields = [new SortField("field3"), new SortField("field2")]
    xlcProducts.source = dataSet.elements("product");
    xlcProducts.sort = mySort;
    xlcProducts.refresh();
    Now I'm dealing with a more complicated XML that follows this structure:
    <products>
         <product>
              <productID>607</productID>
              <productName>ADS1000</productName>
              <features>
                   <featureData>
                        <featureName>feature1</featureName>
                        <featureValue>value1</featureValue>
                   </featureData>
                   <featureData>
                        <featureName>feature2</featureName>
                        <featureValue>value2</featureValue>
                   </featureData>
                   <featureData>
                        <featureName>feature3</featureName>
                        <featureValue>value3</featureValue>
                   </featureData>
              </features>
         </product>
         <product>
              <productID>607</productID>
              <productName>ADS1000</productName>
              <features>
                   <featureData>
                        <featureName>feature1</featureName>
                        <featureValue>value1</featureValue>
                   </featureData>
                   <featureData>
                        <featureName>feature2</featureName>
                        <featureValue>value2</featureValue>
                   </featureData>
                   <featureData>
                        <featureName>feature3</featureName>
                        <featureValue>value3</featureValue>
                   </featureData>
              </features>
         </product>
    </products>
    My problem here is that the same approach doesn't seem to work, when I create the mySort object to assign to the XMLListCollection I can't seen to be able to point it to a field that is not on the top level of the XML's children. Here, I need to sort the XML by featureValue for two different features (which will change at different points in time)
    I've tried to do stuff like this to no avail:
    mySort.fields = [new SortField("features.featureData.(featureName == \"feature3\").featureValue"), new SortField("features.featureData.(featureName == \"feature2\").featureValue")]
    I'm assuming I can't have XML queries in the SortField's name, but nothing else I've tried has worked.

    Yeah, I actually started working on that approach earlier today.
    Thanks for the confirmation.

  • Populate flex tree control on demand using HTTPService (Flex 3)

    First, I am sorry if the same post is already posted here but after spending 30 minutes or may be more I could not find the solution.
    By the way I have two problems. 1.) I am new to flex which I know if my own problem and soon I will handle it.
    2.) This is major problem for me. I have to populate Tree control from database and I used HTTPService to get the data from database.
    I created a object of HTTPService and on load of Tree control I am calling a function which calls the HTTP URL and returns me the first level of node for my Tree.
    When I click on any node a function is called again using HTTPService and result is appended to the currently selected node. The same goes until n level and it works fine. I was happy with my results. I am stuck in new problem. The problem is if the tree is already populated on my browser and I make some add/update/delete any node or child node, the flex doesn't make a call to HTTP URL and I am not getting updated data.
    The mxml code is below (this code has some extra things too).
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
    layout="vertical"  backgroundGradientAlphas="[1.0, 1.0]"
    backgroundGradientColors="[#000000, #868686]" >
    <mx:Script>
      <![CDATA[
       import mx.utils.StringUtil;
       import mx.rpc.http.HTTPService;
       import mx.events.ListEvent;
       import mx.binding.utils.BindingUtils;
       import mx.controls.Alert;
       import mx.rpc.events.FaultEvent;
       import mx.collections.XMLListCollection;
       import mx.utils.ObjectProxy;
       import mx.collections.ArrayCollection;
       import mx.rpc.events.ResultEvent;
       import mx.utils.ArrayUtil;
       [Bindable]
       public var datalist:XMLListCollection = new XMLListCollection();
       [Bindable]
       public var xmlFromDatabase:HTTPService=new HTTPService();
       [Bindable]
       private var xmlForChildren:HTTPService;
       private function resultHandler( event:ResultEvent ):void
           var x:XML = event.result as XML;   
           var xl:XMLList = XMLList( x );
       private function faultHandler( event:FaultEvent ):void
        Alert.show(event.message.toString());
       private function display():void
        var params:Object = {};
        params["parent"] = "0";
        xmlFromDatabase.url = "http://localhost:8080/GrailsFlex/department/tree";
        xmlFromDatabase.method = "GET";
        xmlFromDatabase.resultFormat = "e4x";
        xmlFromDatabase.useProxy = false;
        xmlFromDatabase.send(params);
        xmlFromDatabase.addEventListener(ResultEvent.RESULT,displyTree,false,0,false);
       private function displyTree(event:ResultEvent):void
        XMLtree1.dataProvider =  event.result;
        XMLtree1.labelField = "@name";
       private function getChilds(event:ListEvent):void
        try
         var xmlTree:Tree = event.currentTarget as Tree;
         var node:XML = xmlTree.selectedItem as XML
         var params:Object = {};
         params["parent"] = node.@id;
         xmlForChildren = new HTTPService();
         xmlForChildren.url = "http://localhost:8080/GrailsFlex/department/tree";
         xmlForChildren.method = "GET";
         xmlForChildren.resultFormat = "e4x";
         xmlForChildren.useProxy = false;
         xmlForChildren.send(params);
         xmlForChildren.addEventListener(ResultEvent.RESULT,appendChild,false,0,false);
         xmlForChildren.addEventListener(ListEvent.ITEM_CLICK,getChilds,false,0,false);
        catch (E:Error)
         Alert.show("getChilds Error:-- " + E.message);
       private function deleteTreeNode(xmlItem:XML):void
        var xmlParent:XML = XML(xmlItem).parent();
        if (xmlParent.@parent == null || StringUtil.trim(xmlParent.@parent) == "")
         xmlParent.@parent = "0";
        if (xmlParent.@parent != "0")
         //Recursive call until I get reach to children of root node
         deleteTreeNode(xmlParent);
        else
         // Now I am at root.
         var xmlRoot:XML = XML(xmlParent).parent();
         var bActualRoot:Boolean = false;
         if (xmlRoot == null)
          xmlRoot = xmlParent;
          bActualRoot = true;
         if (bActualRoot)
          if (xmlRoot.@parent == "0")
           try
            for each (var xl:XML in xmlParent.children())
             if (xl.@name != xmlItem.@name)
              for (var cn:int=xl.children().length()-1; cn >=0; cn--)
               delete xl.children()[cn];
           catch (ex:Error)
            Alert.show("error Real Root: " + ex.toString());
         else
          for each (var nodexm:XML in xmlRoot.children() )
           if (nodexm.@name != xmlParent.@name )
            try
             for (var cu:int=nodexm.children().length()-1; cu >=0; cu--)
              delete nodexm.children()[cu];
            catch (ex:Error)
             Alert.show("error No Real Root: " + ex.toString());
       private function appendChild(event:ResultEvent):void
        var node:XML = event.result as XML
        var sItem: XML = XMLtree1.selectedItem as XML;
        if (sItem.children().length() > 0)
         delete sItem.children();
        for(var i:int=0; i < node.children().length(); i++)
                        var item:XML = node.children()[i];
                        XMLtree1.selectedItem.appendChild(item);
                        XMLtree1.expandItem(XMLtree1.selectedItem,true,true);
        deleteTreeNode(XML(XMLtree1.selectedItem));
      ]]>
    </mx:Script>
    <mx:Tree id="XMLtree1" width="350" height="470"
          showRoot="false" creationComplete="display()" itemClick="getChilds(event)"  />
    </mx:Application>
    Thanks in advance

    Thanks buddy for the answer.
    Unfortunately the answer came after quite long time of posting the message. Anyway I was able to open a tree on demand using HttpService and due to my new requirement I changed it to RemoteObject.
    I my latest change I am able to populate tree nodes on demand and also the same solution if getting update from server via JMS using Consumer object.
    I kind a like this solution because it took me good amount of effort to find the right solution.
    If any one is intersted the he/she can reply to the post and I can provide code here or may at some location so that it can be easily downloaded.
    The solution is Flex-Grails combination.
    Thanks everybody.

  • Duplicated entries in Dictionary

    I came from Java to ActionScript so Dictionary object is always a bit strange to me. Today I encountered a weird situation on it which had cost me a few hours of debug time. What I need to do is to find out the common ancestor of two branches in XML. I use Dictionary and the XML node as key. It then all boils down to following snippet:
    var project:XML = <project><item id="item1"/><item id="item2"/></project>
    var item1:XML = project.children()[0];
    var item2:XML = project.children()[1];
    var parent1:XML = item1.parent() as XML;
    var parent2:XML = item2.parent() as XML;
    var dic:Dictionary = new Dictionary();
    dic[parent1] = "1";
    dic[parent2] = "2";
    I expected dic to have only one entry. However it turned out as two entries even though parent1 == parent2 and parent1 === parent2 all test to true. Is this a problem with Dictionary or is it because I used XML as the key and the parent() method whose return type is * is causing the problem? Any help is greatly appreciated! Thanks.
    Regards,
    Feng

    Thanks for the reply. You are right. I could have compared parent() for the scenario I described. However I need to accomplish something else at the same time which was why I used Dictionary. I got my program to work in another way. Nontheless the original question regarding the Dictionary behavior remains. My current observation is that XML node itself works fine as Dictionary key. It's probably the untype nature of parent() method that caused the problem. Dictionary documentation isn't very clear on this (it only stress on strict equality which is satisfied in my snippet). Can anyone confirm?

  • A question about AdvancedDatagridColumnGroup

    Hi guys,
         Just a quick question about AdvancedDatagridColumnGroup, is the children property only allowed to have an AdvancedDatagridColumn on it?
    Because what I'm trying to do is in my recursive function I'm trying to create a nested AdvancedDataGridColumnGroup, all good until I set the ADG's groupedColumns to a certain array which is a return array of the recursive function. It throws out an exception something in the groupedValidation function of ADG.
    Here's the code that does that
    var createColumnGroup:Function = function( group:Array, xml:* ) : Array
                                  var ret:Array = new Array;
                                  var colGroup:AdvancedDataGridColumnGroup = newAdvancedDataGridColumnGroup;
                                  for(var index:int = 0; index < 1; ++index){
                                        var parts:Array = String(group[index]).split(DELIMITER);
                                        if(parts.length){
                                              colGroup = new AdvancedDataGridColumnGroup;
                                              colGroup.headerText = parts[0];
                                              colGroup.children = [];
                                              var curHeader:String = parts[0];
                                              parts.splice(0,1);
                                                                                         //this is the part where I'm trying to nest the advancedDataGridColumnGroup
                                                                                         // what's to be replaced in this line to make a valid nest of ADGColumnGroup?
                                              if( parts.length > 0){
                                                    colGroup.children.push( createColumn([parts.join(DELIMITER)], xml));
                                                                                ret.push( colGroup )
                                  return ret;
    and I call it like this
    var gCols:Array = createColumn( colsArr, new XML(_xml.children()[0].toString()));
    adg.groupedColumns = gCols;
    Best Regards,
    jd

    Your problem is you have iDVD 4 or earlier. Such versions ONLY supported internal SuperDrives.
    PatchBurn at http://www.patchburn.de/faq.html may help you.

  • Weird textinput behavior embedded font

    I have this weird behavior with an embedded font in a textinput.
    I have embedded the myriad font and aplied it on a textinput.
    In this weird scenrio when i type "test configuration" in the textinput and then pres the left arrow key the cursors will not go further back than the letter n in the word configuration.
    This behavior is only with some font types, like myriad or ubuntu.
    Since i have no clue how to upload attachments to this forum i created a Box link
    https://www.box.com/s/0boj6u2kgmwojbg9ubhd
    In here i have a video of the behavior and a test project.

    Not sure if this will help you, but in order to get my embedded fonts to render, I had to do:
                    GlobalSettings.resolveFontLookupFunction = null;
                    //setup text item from xml
                    var res:XML = XML(xml.htmlText.children()[0]);
                    var tf:TextFlow = TextFlowUtil.importFromXML(res,WhiteSpaceCollapse.PRESERVE);
                    tf.renderingMode = RenderingMode.CFF;
                    tf.fontLookup = FontLookup.EMBEDDED_CFF;
                    txt.textFlow = tf;
                    txt.textFlow.whiteSpaceCollapse = WhiteSpaceCollapse.PRESERVE;
                    txt.textFlow.invalidateAllFormats();
    The important lines ar the first and last.

  • Xmdom problem, xmlns = ""  !

    Firstly sorry if am use the wrong terminology (newbie)
    I am using xmldom to create XML documents, I need to set a xmlns attribute againt the root node, but when generating the xml, the children nodes are inheriting the namespace attribute, and setting it to null (xmlns = ""). I read this is default behaviour but our client will not accept xml like this. On Oracle 8i I was not getting this, but I am getting it with 9.2 ? Any ideas ? Any workarounds ?
    Ed

    Sorry I dont know how do do that in PLSQL , I am using the XMLDOM package , i am trying to get this
    <?xml version = '1.0' encoding = 'ASCII'?>
    <UpdateParameters xmlns="http://schemas//UpdateParamete
    rs.xsd">
    <ADD>
    <Category>TMSDBTEST2</Category>
    </ADD>
    </UpdateParameters>
    but I get <ADD xmlns=""> instead of <ADD>
    Any ideas ? cheers !

  • FilterFunction on multiple levels

    I am using filterFunction on a XMLListCollection to filter
    data. It works fine except it only filters the first level of data.
    Is there someway to have it filter all levels of the XML (all
    children levels / nodes)?
    Or is there away to assign a new filterFunction on each level
    of XML?

    quote:
    Originally posted by:
    egeddes
    http://blog.flexexamples.com/2007/08/22/sorting-and-filtering-data-in-an-xmllistcollection /
    Thanks for the reply but that example only handles one level
    of filtering. I have seen several examples like this. The real
    challenge is filtering on multiple levels.

  • Add all values from xml.children()

    I have an xml of numbers that I am using to power some dynamic bar charts..
    I can easily pull out a string of all node values for variable area (SQMI)
    trace(stsXml.Records.Record.SQMI.children());
    the trace result looks like this
    6729014724597803833449707411067084872157776104101113713121757
    these values do not appear to be seperated but I am hoping they are (there should be 11 unique values here).
    How can I sum the 11 values as extracted from my XML?

    After some googling I was able to find some code and apply it to my problem...  The hard part is that I do not fully understand why this works.  For example, what is "xl" doing?
    function sumXML(stsXml:XML):Number {
                var r_num:Number = 0;
                for each(var xl:XML in stsXml..SQMI){
                    r_num += parseFloat(xl.text());
                return Number(r_num.toFixed(2));
            trace(sumXML(stsXml));

  • Xml newbie - multiple loops for children in xml?

    Hi all,
    I am hoping someone can help me with this!
    I have what I guess is a pretty basic xml that I need to parse and insert in a table. I have the basic code where I loop through the node list and assign values in the table type, and then insert into the table.
    However, I have multiple levels of data that I plan to insert in one de-normailized table. So, for example:
    <POHDR>
    .. some fields...
    <POLINE>... several fields of info ...
    <PODISTLINE> ... more pieces of info ...
    </PODISTLINE>
    </POLINE>
    <POLINE>... several fields of info ...
    <PODISTLINE> ... more pieces of info ...
    </PODISTLINE>
    <PODISTLINE> ... more pieces of info ...
    </PODISTLINE>
    </POLINE>
    .. multiple such lines
    <POHDR>
    <POHDR>
    <POLINE>... several fields of info ...
    <PODISTLINE> ... more pieces of info ...
    </PODISTLINE>
    </POLINE>
    <POLINE>... several fields of info ...
    <PODISTLINE> ... more pieces of info ...
    </PODISTLINE>
    <PODISTLINE> ... more pieces of info ...
    </PODISTLINE>
    </POLINE>
    .. multiple such lines
    <POHDR>
    All this would go in one staging table with multiple lines of po_header, po_lines and distribution lines information.
    I have the pretty basic generic code, where I do the loop and assign values:
    v_parser := xmlparser.newParser;
    xmlparser.parseclob (v_parser, p_po_clob_file);
    v_doc := xmlparser.getDocument (v_parser);
    xmlparser.freeparser (v_parser);
    v_po_nl := xslprocessor.selectNodes(xml.makeNode(v_doc), 'POFILE');
    FOR i in 0.. sys.xmldom.getLength(v_po_nl)-1 LOOP
    v_po_n := sys.xmldom.item(v_po_nl, i)
    v_po_rec.extend;
    v_po_rec(v_po_rec.last).ponum := sys.xslprocessor.valueOf(v_po_n, 'PONUM');
    ...... etc.
    ... and then the insert.
    But I don't know what to do about getting the PO line and PO Distribution line child items. I guess I could do :
    v_po_rec(v_po_rec.last).polinnum := sys.xslprocessor.valueOf(v_po_n, 'POLINNUM');
    but wouldn't I need to do another loop to find the child line items - and then another to get line distributions?
    Please help!
    Thanks a lot!

    Thanks - and yes, understood.
    However, my XMLType data is not in a XMLType table (just a column of a regular table), so I cannot use the extract functions.
    I am not using XML Schemas - right now that is not in the works. We may look into that later.
    I did try using xmlsave - but again, that just saves the data in top rowset (PO Header, and does not insert any line items in the table)
    Isn't there a way to do this with just a loop? I tried looking at your child example Re: How to use PL/SQL to read and manipulate data from a xml file , but that does not loop to go through multiple children..
    Is there a way to do this with a loop using xmldom? Or a way to do it using xmlsave (but also saving the child rowsets?
    Again, any help will be most appreciated - if you can tell me there isn't then I will look into one of the other options.
    Thanks again!

  • XML having many parents and many children but all unrelated!***URGENT***

    This is very urgent..Please HELP!!!
    Iam in a project which is planning to store the entire XML file in the database in a XML datatype column. The XML has multiple parents AND multiple children for each of those parents. My problem is how to read/store the data for each of the parent and associate the parent to the child elements. The child elements does not have a parentID in its column. Here is an example- Parent table - SHIPMENT. Child Table - SHIPMENTUNITS. ShipmentNBr is the business key in both these tables. This column comes in the SHIPMENT node but does not come in the SHIPMENTUNITS node. When I try the OPENXML, all the data just gets stored..how do I link the child to the parent?
    <SHIPMENT xmlns="">
    <SHIPMENTNBR>US1011<SHIPMENTNBR />
    <SHIPMENTTYPE_CD>BK</SHIPMENTTYPE_CD>
    <LINESCAC>ACLH</LINESCAC>
    <TERMINAL_CD>USJAX</TERMINAL_CD>
    <ISSUE_DT>2006-08-17T14:23:09</ISSUE_DT>
    <VESSEL_CD>VES</VESSEL_CD>
    <VOYAGE_CD>VOYA</VOYAGE_CD>
    <POL />
    <POD>POD_0</POD>
    <SHIPMENTUNITS>
    <UNITNBR>1234</UNITNBR>
    <UNITTYPE_CD>CAR</UNITTYPE_CD>
    <MAKE>HON</MAKE>
    <MODEL>ACCO</MODEL>
    <COLOR>RED</COLOR>
    <FULLEMPTY_CD>F</FULLEMPTY_CD>
    <LENGTH>0011</LENGTH>
    <WIDTH>0022</WIDTH>
    <HEIGHT>0033</HEIGHT>
    <DIMENSIONUOM>C</DIMENSIONUOM>
    <WEIGHT>000010</WEIGHT>
    <WGTUOM>K</WGTUOM>
    </SHIPMENTUNITS>
    </SHIPMENT>
    <SHIPMENT xmlns="">
    <SHIPMENTNBR>IN2052<SHIPMENTNBR />
    <SHIPMENTTYPE_CD>BK</SHIPMENTTYPE_CD>
    <LINESCAC>ACLH</LINESCAC>
    <TERMINAL_CD>USJAX</TERMINAL_CD>
    <ISSUE_DT>2006-08-17T14:23:09</ISSUE_DT>
    <VESSEL_CD>VES</VESSEL_CD>
    <VOYAGE_CD>VOYA</VOYAGE_CD>
    <POL />
    <POD>POD_0</POD>
    <SHIPMENTUNITS>
    <UNITNBR>1234</UNITNBR>
    <UNITTYPE_CD>CAR</UNITTYPE_CD>
    <MAKE>HON</MAKE>
    <MODEL>ACCO</MODEL>
    <COLOR>RED</COLOR>
    <FULLEMPTY_CD>F</FULLEMPTY_CD>
    <LENGTH>0011</LENGTH>
    <WIDTH>0022</WIDTH>
    <HEIGHT>0033</HEIGHT>
    <DIMENSIONUOM>C</DIMENSIONUOM>
    <WEIGHT>000010</WEIGHT>
    <WGTUOM>K</WGTUOM>
    </SHIPMENTUNITS>
    </SHIPMENT>

    I don't quite understand what you want to achieve.
    If you store the data in an XML data type then you get the XML as is and all the children are associated with their parents.
    If you want to decompose them into relational tables using OpenXML, then you either use the id values provided in the data and use the parent axis, or if no such id values are present look at the so called meta properties @mp:id and @mp:parentid. In your case you have the shipment number and unit number that you could use. The first approach you can do with the nodes() method too (but the meta properties are OpenXML only).
    In the following example I show you both. In your case you don't need the @mp: parts. Also, since OpenXML needs a complete document I added a single root node.
    declare @i int;
    exec sp_xml_preparedocument @i output,
    N'<doc><SHIPMENT xmlns="">
      <SHIPMENTNBR>US1011</SHIPMENTNBR>
      <SHIPMENTTYPE_CD>BK</SHIPMENTTYPE_CD>
      <LINESCAC>ACLH</LINESCAC>
      <TERMINAL_CD>USJAX</TERMINAL_CD>
      <ISSUE_DT>2006-08-17T14:23:09</ISSUE_DT>
      <VESSEL_CD>VES</VESSEL_CD>
      <VOYAGE_CD>VOYA</VOYAGE_CD>
      <POL />
      <POD>POD_0</POD>
      <SHIPMENTUNITS>
        <UNITNBR>1234</UNITNBR>
        <UNITTYPE_CD>CAR</UNITTYPE_CD>
        <MAKE>HON</MAKE>
        <MODEL>ACCO</MODEL>
        <COLOR>RED</COLOR>
        <FULLEMPTY_CD>F</FULLEMPTY_CD>
        <LENGTH>0011</LENGTH>
        <WIDTH>0022</WIDTH>
        <HEIGHT>0033</HEIGHT>
        <DIMENSIONUOM>C</DIMENSIONUOM>
        <WEIGHT>000010</WEIGHT>
        <WGTUOM>K</WGTUOM>
      </SHIPMENTUNITS>
    </SHIPMENT>
    <SHIPMENT xmlns="">
      <SHIPMENTNBR>IN2052</SHIPMENTNBR>
      <SHIPMENTTYPE_CD>BK</SHIPMENTTYPE_CD>
      <LINESCAC>ACLH</LINESCAC>
      <TERMINAL_CD>USJAX</TERMINAL_CD>
      <ISSUE_DT>2006-08-17T14:23:09</ISSUE_DT>
      <VESSEL_CD>VES</VESSEL_CD>
      <VOYAGE_CD>VOYA</VOYAGE_CD>
      <POL />
      <POD>POD_0</POD>
      <SHIPMENTUNITS>
        <UNITNBR>1234</UNITNBR>
        <UNITTYPE_CD>CAR</UNITTYPE_CD>
        <MAKE>HON</MAKE>
        <MODEL>ACCO</MODEL>
        <COLOR>RED</COLOR>
        <FULLEMPTY_CD>F</FULLEMPTY_CD>
        <LENGTH>0011</LENGTH>
        <WIDTH>0022</WIDTH>
        <HEIGHT>0033</HEIGHT>
        <DIMENSIONUOM>C</DIMENSIONUOM>
        <WEIGHT>000010</WEIGHT>
        <WGTUOM>K</WGTUOM>
      </SHIPMENTUNITS>
    </SHIPMENT></doc>'
    select *
    from OpenXML(@i, '/doc/SHIPMENT')
            with (
                     id int '@mp:id'
                   , nbr varchar(40) 'SHIPMENTNBR'
    select *
    from OpenXML(@i, '/doc/SHIPMENT/SHIPMENTUNITS')
            with (
                     id int '@mp:id'
                   , ship_id int '@mp:parentid'
                   , ship_nbr varchar(40) '../SHIPMENTNBR'
                   , nbr varchar(40) 'UNITNBR'
    exec sp_xml_removedocument @i
    Best regards
    Michael

  • Pulling in children of children in XML

    Hey all-
    Newbie to XML here and I have what I *hope* is an easy
    problem, but I just don't know the answer. And as I have to try and
    show this by Monday, I'm sort of stuck.
    I am trying to pull in information about houses via an xml
    file. Each house has 1 address, 1 owner, 1 description, and about 6
    photos. I have no problem accessing the address, owner, etc, and I
    can always access the first photo, but whenever I cycle through the
    photos, I seem to cycle through the first photo for every house,
    not every photo for each house.
    Basically, I need the children <images> to go up by
    one, without the the parent going up by 1. I am hoping I am
    describing this well.
    My code looks like this:
    total = xmlNode.childNodes.length;
    totalb =
    xmlNode.childNodes[0].childNodes[5].childNodes.length;
    totalc = (totalb-1);
    for (i=0; i<total; i++) {
    thumb
    = xmlNode.childNodes.childNodes[0].firstChild.nodeValue;
    address
    = xmlNode.childNodes.childNodes[1].firstChild.nodeValue;
    construct
    = xmlNode.childNodes.childNodes[2].firstChild.nodeValue;
    work
    = xmlNode.childNodes.childNodes[3].firstChild.nodeValue;
    description
    = xmlNode.childNodes.childNodes[4].firstChild.nodeValue;
    image
    =
    xmlNode.childNodes.childNodes[5].firstChild.firstChild.nodeValue;
    where total = number of houses
    and totalb = number of photos for that house.
    This works fine - it is pulling in the accurate number of
    both houses and photos.
    My XML looks like this:
    <projects>
    <pic>
    <thumb>boulevard_staircase1_thumb.jpg</thumb>
    <address>Jim's Place</address>
    <construct>July 28, 2006</construct>
    <work>Framing, Electrical, Flooring,
    Roofing</work>
    <description>This is Jim's place</description>
    <photos>
    <image>jim1.jpg</image>
    <image>jim2.jpg</image>
    <image>jim3.jpg</image>
    <image>4.jpg</image>
    <image>jim5.jpg</image>
    </photos>
    </pic>
    <pic>
    <thumb>boulevard_staircase1_thumbb.jpg</thumb>
    <address>Bob's Place</address>
    <construct>January 20, 2006</construct>
    <work>Bob's Stuff</work>
    <description>Isn't Bob Great?</description>
    <photos>
    <image>bobs1.jpg</image>
    <image>bobs2.jpg</image>
    <image>bobs3.jpg</image>
    <image>bobs4.jpg</image>
    </photos>
    </pic>
    <image> is the tag I am having problem with.
    THANKS a lot, and a frosty beer to whoever can help!
    Noah

    I suggest you load your XML nodes in to an Array for each
    nodevalue
    then you can cycle thru the array for each pic rather than
    trying to extract each childnode value.
    A simple way to do this is using XPath statements to load
    Arrays
    Try this
    import mx.xpath.XPathAPI;
    var projectxml:XML = new XML();
    projectxml.ignoreWhite = true;
    projectxml.onLoad = function(success:Boolean) {
    trace("onload...");
    if (success) {
    trace("success...");
    var thePath_str:String = "projects/pic/photos";
    var pic_array:Array =
    XPathAPI.selectNodeList(this.firstChild, thePath_str);
    // then you can use a loop to step thru the images
    for (var i:Number = 0; i < title_array.length; i++) {
    trace(pic_array
    .firstChild.nodeValue);
    projectxml.load("project.xml");
    You can extend this to load all your node values into arrays
    then you can step thru the data far more easily.

Maybe you are looking for