简体   繁体   中英

Better way to build XML string via Javascript

I currently have the below to build up a XML string which will get sent via a socket and was wondering if there was a better way to build it in terms of readability.

I thought I had read somewhere where you can have shortcut type ways of adding elements to the DOM but didn't know if this applied to strings/XML objects.

        var jqInputs = $('input', nRow);  //Get all inputs
        var updatedValues = [];

        jqInputs.each(function (idx) {
            updatedValues.push($(this).val());  //Put values into array
        });

        //Get table columns
        var cols = $('th').filter(function (index) {
            return $(this).text() != "" && $(this).text() != "Edit";
        });

        var colnames = [];

        //Get table column names and put into array
        $.each(cols, function () {
            colnames.push($(this).text());
        });

        //Build up XML and send to server
        if (updatedValues.length == colnames.length) {
            //******************************
            //** IS THERE A BETTER WAY TO DO THIS?????**
            //******************************
            var xmlvalue;
            for(var i = 0; i < updatedValues.length;i++)
            {
                 xmlvalue = xmlvalue + '<' + colnames[i] + '>' + updatedValues[i] + '<\' + colnames[i] + '>'
            }
            socket.send('<Root>'+ xmlvalue +'<UserID>1</UserID></Root>');
        }

Can you use e4x ? If so, xml is a piece of cake:

var xmlv = <Root />;
for(var i = 0; i < updatedValues.length;i++)
   xmlv.appendChild(<{colnames[i]}>{updatedValues[i]}</{colnames[i]}>);
xmlv.appendChild(<UserID>1</UserID>);
socket.send(xmlv.toXMLString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM