Reputation: 25
In my code I have converted data from a JSON Model into XML. To ensure correct formatting I parse my created XML string into XML Doc. (API cannot work with XML that is not well formatted)
Therefore, I need some help converting my XML Doc variable into Base64 (instead of my XML string) using Javascript.
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlDataString,"text/xml");
Does anyone know a function besides btoa() which is used for converting strings?
Using btoa(xmlDataString) returns API error "Xml parsing error: not well formed" and using btoa(xmlDoc) returns Base64 which returns when decoded again: "[object XMLDocument]"
Thanks
Upvotes: 1
Views: 9825
Reputation: 12822
Serialize your XML and then convert to Base64: (new XMLSerializer()).serializeToString(xml);
prolog = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';
var parser = new DOMParser();
XmlStr = prolog + "<bookz/>";
var xmlz = parser.parseFromString(XmlStr, "application/xml");
console.log(window.btoa((new XMLSerializer()).serializeToString(xmlz)));
Result:
PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9InllcyI/Pgo8Ym9va3ovPg==
Upvotes: 0