Netzz

tips collection

NAVIGATION - SEARCH

Create XML using jQuery

With jQuery you can manipulate XHTML documents and create HTML fragments.

But you can also create XML documents and serialize them to string:

var doc = $.parseXML('<?xml version="1.0" encoding="utf-8" ?><Root xmlns="http://www.w3.org/1999/xhtml" />');
var $Root = $(doc.documentElement);
$('<cmd>').appendTo($Root).attr('Upper', 'val').text('action');
var xml=(new XMLSerializer()).serializeToString(doc)
//var xml=$("<dummy>").append($Root.clone()).html();
$(document.body).text(xml);

To be sure attributes are not lowered you have to append the element to it's parent before setting attributes.

You can also create an XML fragment in the same way:

var doc = $.parseXML('<Root />');
var $Root = $(doc.documentElement);
$('<cmd>').appendTo($Root).attr('Upper', 'val').text('action');
var xml=(new XMLSerializer()).serializeToString(doc)
//var xml=$("<dummy>").append($Root.clone()).html();
$(document.body).text(xml);

 

blog comments powered by Disqus