开发者

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());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜