javascript: serialize as xml
By Anatoly Mironov
Why should we need to serialize javascript objects as XML. I don’t know. It is of course more a server side need. And there actually a need for javascript serialization as xml in node.js. To serialize as json is very simple: JSON.stringify(myobjects). I was just curious if there was a tool for xml serialization in javascript. There is a nice javascript tool called XMLWriter, developed by Ariel Flesler. Consider you have articles and want to serialize them as xml, let’s create a function for serializing:
function createProductXML(articles) {
var v = new XMLWriter( 'UTF-8', '1.0' );
v.indentChar = " ";
v.writeStartDocument();
v.writeStartElement('articles');
for(var a in articles) {
var article = articles\[a\];
v.writeStartElement('article');
v.writeAttributeString('summercollection',article.summercollection.toString());
v.writeAttributeString('wintercollection',article.wintercollection.toString());
v.writeElementString('name', article.name);
v.writeElementString('number', article.number);
v.writeElementString('description', article.description);
v.writeElementString('price', article.price.toString());
v.writeElementString('quantity', article.quantity.toString());
v.writeStartElement('categories');
for(var c in article.categories) {
v.writeElementString('category', article.categories\[c\]);
}
v.writeEndElement();
v.writeEndElement();
}
v.writeEndDocument();
return v.flush();
}
```And now we can test it:
var articles = []; articles.push({ name: “Ski”, number: “X21”, description: “The best ski for beginners”, summercollection: false, wintercollection: true, price: 20.5, quantity: 20, categories: [“winter”, “snow”, “fun”, “beginner”] }); articles.push({ name: “Helicopter”, number: “T21”, description: “The best helicopter toy ever”, summercollection: true, wintercollection: false, price: 40, quantity: 10, categories: [“toy”, “fly”, “fun”, “children”] }); articles.push({ name: “Book”, number: “B21”, description: “The best book ever”, summercollection: true, wintercollection: true, price: 100, quantity: 5, categories: [“reading”, “education”, “fun”, “puzzle”] }); var xml = createProductXML(articles); console.log(xml);