Search code examples
javascriptxmlsoapescapinge4x

Creating a loop mid-E4X declaration


I am working with some legacy code and have to update a SOAP request that is built using E4X. I have an array of data that I need to loop through and build repeating XML-segments and insert them into the SOAP request. My pseudo example...

var myData = ['apples','oranges','pears','grapes'];

var myFruit;
for( var i=0; i<myData.length; i++ ){
    myFruit += <fruit>{myData[i]}</fruit>;
}

var request = <soapenv:Envelope>
<soapenv:Header></soapenv:Header>
<soapenv:Body>
    <MyFruitList>
        {myFruit}
    </MYFruitList>
</soapenv:Body>
</soapenv:Envelope>;

This works EXCEPT all of the tags in {myFruit} appear to have been escaped.. it looks like this..

<soapenv:Envelope>
<soapenv:Header></soapenv:Header>
<soapenv:Body>
    <MyFruitList>
        &lt;fruit&gt;apples&lt;/fruit&gt;
        &lt;fruit&gt;oranges&lt;/fruit&gt;
        &lt;fruit&gt;pears&lt;/fruit&gt;
        &lt;fruit&gt;grapes&lt;/fruit&gt;
    </MYFruitList>
</soapenv:Body>
</soapenv:Envelope>;

.. this then fails on the other end of my SOAP request... any help?


Solution

  • The end-result of this problem was rather simple, but is a biiit hacky.

    When I create my E4X object I simply put in a placeholder element... example...

    var myData = ['apples','oranges','pears','grapes'];
    
    var myFruit;
    for( var i=0; i<myData.length; i++ ){
        myFruit += <fruit>{myData[i]}</fruit>;
    }
    
    var request = <soapenv:Envelope>
        <soapenv:Header></soapenv:Header>
        <soapenv:Body>
            <MyFruitList>
                <fruitList/>
            </MyFruitList>
        </soapenv:Body>
    </soapenv:Envelope>;
    

    Later, I'm converting the whole object string before I submit the SOAP request.. so after the string conversion I simply did a string replace.

    var requestString = request.toString();
    requestString = requestString.replace("<fruitList/>",myFruit);