Create Well-Formed XML with JavaScript
Use Javascript to ensure that you write correct, well-formed XML in web pages.
Sometimes you need to create some XML from within a browser. It is easy to write bad XML without realizing it. Writing correct XML with all its bells and whistles is not easy, but in this type of scenario you usually only need to write basic XML.
There is a kind of hierarchy of XML:
Basic: Elements only; no attributes, entities, character references, escaped characters, or encoding issues
Plain: Basic plus attributes
Plain/escaped: Plain with special XML characters escaped
Plain/advanced: Plain/escaped with CDATA sections and processing instructions
The list continues with increasing levels of sophistication (and difficulty).
This hack covers the basic and plain styles (with some enhancements), and you can adapt the techniques to move several more steps up the ladder if you like.
The main issues with writing basic XML is to get the elements closed properly and keep the code simple. Here is how.
The Element Function
Here is a Javascript function for writing elements:
// Bare bones XML writer - no attributes
function element(name,content){
var xml
if (!content){
xml='<' + name + '/>'
}
else {
xml='<'+ name + '>' + content + '</' + name + '>'
}
return xml
}This basic hack even writes the empty-element form when there is no element content. What is especially nice about this hack is that you can use it recursively, like this:
var xml = element('p', 'This is ' + element('strong','Bold ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access