标签:
如何从一个 HTML 表单生成对应的 XML 呢?在我们为应用程序创建一个简单的 Web 服务接口的时候可能会用到它,来看看这个函数:
/*设置一个命名空间防止冲突*/ if ( typeof jscript == ‘undefined‘ ) { jscript = function () { } } jscript.form = function () { } /** * This function takes an HTML form and constructs an XML document from it, * using the specified root element. *(这个函数把 HTML 表单中的信息转换为 XML document) * @param inForm A reference ot the HTML form object to serialize. * @param inRootElement The root element the XML dccument should use. * @return A string of XML constructed from serializing the * specified form.(此参数为 XML document 的根元素) */ jscript.form.formToXML = function (inForm, inRootElement) { if (inForm == null ) { return null ; } if (inRootElement == null ) { return null ; } var outXML = "<" + inRootElement + ">" ; var i; /*开始处理*/ for (i = 0; i < inForm.length; i++) { var ofe = inForm[i]; var ofeType = ofe.type.toUpperCase(); var ofeName = ofe.name; var ofeValue = ofe.value; /*处理不同的 input 框及 select 和 textarea,"SELECT-ONE" 为单选模式*/ if (ofeType == "TEXT" || ofeType == "HIDDEN" || ofeType == "PASSWORD" || ofeType == "SELECT-ONE" || ofeType == "TEXTAREA" ) { outXML += "<" + ofeName + ">" + ofeValue + "</" + ofeName + ">" } /*处理 select 的多选(multiple)模式*/ if (ofeType == "SELECT-MULTIPLE" ){ outXML += "<" + ofeName + ">" ; for (j = 0; j < ofe.options.length; j ++){ outXML += "<option" + (j + 1) + ">" ; outXML += "<text>" + ofe.options[j].innerHTML + "</text>" ; outXML += "<value>" + ofe.options[j].value + "</value>" ; outXML += "</option" + (j + 1) + ">" ; } outXML += "</" + ofeName + ">" ; } /*处理单选框(radio)*/ if (ofeType == "RADIO" && ofe.checked == true ) { outXML += "<" + ofeName + ">" + ofeValue + "</" + ofeName + ">" } /*处理多选框*/ if (ofeType == "CHECKBOX" ) { if (ofe.checked == true ) { cbval = "true" ; } else { cbval = "false" ; } outXML = outXML + "<" + ofeName + ">" + cbval + "</" + ofeName + ">" } outXML += "" ; } outXML += "</" + inRootElement + ">" ; return outXML; } // End formToXML(). |
来看一个表单,试试这个函数的效果:
< form id="testForm"> < input type="text" name="firstName" value="Jack">< br > < input type="text" name="lastName" value="Redd">< br > < select multiple id="numComputers" name="numComputers"> < option value="1">I own one computer</ option > < option value="2">I own two computers</ option > < option value="2+">I own two or more computers</ option > </ select > </ form > |
通过表单元素来调用函数:
jscript.form.formToXML(document.getElementById( ‘testForm‘ ), ‘Person‘ ) |
来看看它的处理结果:
< Person > < firstName >Jack</ firstName > < lastName >Redd</ lastName > < numComputers > < option1 > < text >I own one computer</ text > < value >1</ value > </ option1 > < option2 > < text >I own two computers</ text > < value >2</ value > </ option2 > < option3 > < text >I own two or more computers</ text > < value >2+</ value > </ option3 > </ numComputers > </ Person > |
具体生成什么格式的 XML 信息要看应用程序的要求,然后通过修改函数来达到目的,这只是一个示例。:->
标签:
原文地址:http://www.cnblogs.com/jin-talk/p/5648810.html