Tuesday, 3 March 2015

Lightweight library to create XML strings from javascript?



Need to generate OpenOffice XML strings on node.js and browser environments including Chrome and IE 10/11.


It seems like writing XML would be a solved problem and a library would exist. Many people upvoted @Jason's advice to use a library not invent ones own.


On Node.js cheerio.js is great. Ok, so you have to add a couple arguments to create a node, as in var $el = cheerio(<'patternFill/>',null,null,{xmlMode:true}) but that's okay.


On the browser, you'd thing jQuery would have this. But I'm going crazy:




  • $('<patternFill') lower cases tag names on creation, so you have to use $el = jQuery.parseXML('') to keep the camel case as XML is case sensitive.




  • jQuery $el.html() lower cases tagnames and includes only the inner HTML, so you have to use $el[0].outerHTML with XMLSerializer instead




  • jQuery outerHTML isn't defined in IE 10 or IE11 (How to reliably convert XML to String in IE 10/11?)




So fine. Writing an XML string seems simple enough.


But then I have to escape quotes and such which brought me to this post, in which What characters do I need to escape in XML documents?


Then it turns out there are different kinds of quotes. What about embedded escaped quotes, such as "\"" -- do I turn that into "\&quot;" or "&quot;"? Etc.


So now it feels like I'm reinventing jQuery and cheerio. This can't be right. Is there a simple Javascript library for writing XML programmatically?


No comments:

Post a Comment