views:

52

answers:

1

Given the following xml:

<form>
    <personalDetails>
        <name>John</name>
    </personalDetails>
    <financeDetails>
        <income>
            <salary>1000000</salary>
        </income>
    </financeDetails>
</form>

I know that is it possible to create the above xml as follows (which is very cool):

var xml:XML = <form />;
xml.personalDetails.name = "John";
xml.financeDetails.income.salary = 1000000;

However, what if we do not know the names of the nodes or how many levels exist? We can accomplish this using the method below but it really feels like there should be an easier, better way to do this:

var xml:XML = <form />;
updateXml(xml, "personalDetails.name", "John");
updateXml(xml, "financeDetails.income.salary", "1000000");

function updateXml(xml:XML, path:String, data:String):void {

    var nodesArray:Array = path.split(".");

    switch (nodesArray.length) {

        case 1: 
            xml[nodesArray[0]] = data;
            break;

        case 2:
            xml[nodesArray[0]][nodesArray[1]] = data;
            break;

        case 3:
            xml[nodesArray[0]][nodesArray[1]][nodesArray[2]] = data;
            break;
    }
}
+1  A: 

Well, I don't know if Flex has any build-in mechanism for dealing with such situation (I don't suppose it does) but I certainly can help you make your function more versatile

function updateXml(xml:XML, path:String, data:String):void {
    var nodesArray:Array = path.split(".");
    var tempXML:XML = xml;
    var tempXMLCandidate:XML;
    var tagName:String;
    for (var i:int = 0; i < nodesArray.length; i++){
        tagName = nodesArray[i];
        if (i == nodesArray.length - 1){
            tempXML[tagName] = data;
        }else{
            tempXMLCandidate = tempXML[tagName][0];
            if (!tempXMLCandidate){
                tempXMLCandidate = <{tagName}>;
                tempXML.appendChild(tempXMLCandidate);
            }
            tempXML = tempXMLCandidate;
        }
    }
}

I keep my fingers crossed however so someone would help you with some build-in solution, I'm curious about it myself.

Cheers.

2DH
I like what you are trying to do here but this will only work if the intermediary nodes already exist in the xml. For example, the following will cause a TypeError (Cannot access a property or method of a null object reference):var xml:XML = <form/>;updateXml(xml, "personalDetails.name", "John");
Pete
Yeah, sorry for that. I've checked if nodes are being created but only at bottom-most level and while that worked I assumed that other worked as well. I've fixed above code so it doesn't throw the exception anymore.
2DH