简体   繁体   中英

Convert XML to Base64 using Javascript

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

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==

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM