Case Study: Live XML Edit
In this section, you apply what you learned to create a browser-based XML editor.
While I don't recommend editing XML by hand, I can think of too many cases where precisely that approach was taken. So, in part as an academic exercise and in part as a useful tool, I set out to build a browser-based XML editor. A primary goal was to process the XML directly, rather than convert it to a different format such as JSON, make the updates, then transform back to XML. Making the edits live ensures that the only affected parts of the file are those that were actually edited, which means less room for error and faster processing. The techniques covered in this tutorial were essential in putting this together. Take a closer look at how they applied.
Figure 2 shows Live XML Edit.
Figure 2. Live XML Edit
LiveXMLEdit uses Ajax to get the XML into the page. The user is required to upload the
XML file he wants to edit, which is then saved on the server, and brought in using
$.ajax() described in Listing 27. A reference to the original XML object is saved and edited directly. This approach means that after the user is finished editing the file no transformations are necessary as the updated DOM already exists.
traverseDOM method (see Listing 11), and each
of the nodes along with their attributes is rendered as nested unordered lists (UL).
jQuery is then used to assign handlers for expanding and collapsing of elements, which
simplifies the display and editing of larger documents. Also rendered are action
buttons that provide editing features.
Along with rendering buttons for editing and deleting nodes and making updates for edited fields, the success handler of the Ajax call that loads the XML also assigns handlers for processing various user interactions and events. jQuery provides different means of assigning handlers, but for unpredictably large DOMs by far the most efficient is the
$.live() method or its younger (and even more performant) sibling,
$.delegate(). Rather than catch events at the target element, these methods handle events at the document or the specified element, respectively. This approach has a number of benefits—faster binding and unbinding, and support for existing as well as future nodes that match the selector (key in this case because users can create new XML nodes that should behave just like existing ones.)
Although server-side processing is beyond the scope of this article, it is necessary for saving the edited file. For the code sample, check out the entire application on GitHub (see Resources), but as far as the browser processing is concerned, simply convert the updated XML DOM to a string and post it to a server script. The script itself retrieves the post and saves it as a file.