|
Summary
This snippet describes an alternate method of binding web form fields to an XML data island using XSLT.
This XSLT stylesheet, when applied to any XML document, will render all text elements and attributes as forms fields which are bound to the original XML document via an XML data island. Changes to the text/attributes automatically update the XML data island, which can then be saved using the Microsoft XMLHTTP object. This is an alternative to data binding using Microsoft's datasrc and datafld attributes, which work well if you know the structure of your XML document beforehand, or if the XML structure is not very complex.
How it works: The XSLT stylesheet parses through the XML document, creating a form field for each text node and attribute, and adds an onblur event to each form field. The first argument to this onblur event is an absolute XPath expression to the current node or attribute, and the second argument is a javascript 'this' pointer to the form field that fired the event. When passed to the following function, they can be used to update the original XML document which is inlined as an XML data island, and can be persisted using the xmlhttp object.
Here is the function used to update a text node:
function updateNode(path,srcObj){ xmlData.selectSingleNode(path).text=srcObj.innerHTML; }
When focus leaves the form field, the event fires and updates the corresponding node in the XML Data island. The only thing left to do is save the XML Document, which can be accomplished using the XMLHTTP object. Alternatively, the xml island could be saved to a hidden field and posted back to the server to be saved.
Here is the source for the HTML file used in conjunction with the XSLT file:
<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 3.2 Final//EN> <HTML> <HEAD> <xml id=xmlData/> <meta http-equiv=Content-Type content=text/html; charset=iso-8859-1> <script language=javascript>
function loadDoc(){ docSrc=document.myForm.fileSrc.value; xmlData.async = false; xmlData.load(docSrc); var xslData = new ActiveXObject(Microsoft.XMLDOM); xslData.async = false; xslData.load(simple.xslt); xmlForm.innerHTML = xmlData.transformNode(xslData.documentElement); }
function showDoc(){ alert(xmlData.xml); }
function updateNode(path,srcObj){ xmlData.selectSingleNode(path).text=srcObj.innerHTML; }
function updateAttribute(path,srcObj){ xmlData.selectSingleNode(path).text=srcObj.value; }
function submitInfo(){ var httpOb = new ActiveXObject(Microsoft.XMLHTTP); httpOb.Open(POST,xmlPostAcceptor.asp, false); httpOb.send(xmlData.xml); } </script> </HEAD> <BODY> <form name=myForm method=post> <input type=button value=load onclick=loadDoc()> <input type=file name=fileSrc> <input type=button value=show doc onclick=showDoc() /> <input type=button value=submit onclick=submitInfo() /><br/><br/> <div id=xmlForm> </div> </form> </BODY> </HTML>
|