xml.ts
1 export class xml { 2 static header = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"; 3 4 static envelope(body: string): string { 5 // aliases to make it shorter... 6 const xmlns = "xmlns"; 7 const w3 = "http://www.w3.org/2001/XMLSchema"; 8 const schemas = "http://schemas.xmlsoap.org/soap/"; 9 10 return `<v:Envelope ${xmlns}:i="${w3}-instance" ${xmlns}:d="${w3}" ${xmlns}:c="${schemas}encoding/" ${xmlns}:v="${schemas}envelope/"><v:Header/><v:Body>${body}</v:Body></v:Envelope>`; 11 } 12 13 static from_entities(encoded: string): string { 14 return encoded 15 .replace(/\</g, "<") 16 .replace(/\>/g, ">") 17 // https://stackoverflow.com/a/27020300 18 .replace(/&#\d+;/gm, function (s) { 19 // @ts-expect-error : we know it's a number 20 return String.fromCharCode(s.match(/\d+/gm)[0]); 21 }); 22 } 23 24 static property(name: string, value: string, type = "string"): string { 25 return `<${name} i:type="d:${type}">${this.to_entities(value)}</${name}>`; 26 } 27 28 static to_entities(decoded: string): string { 29 return decoded 30 // https://stackoverflow.com/a/27020300 31 .replace(/./gm, (s) => { 32 return (s.match(/[.<>a-z0-9\s]+/i)) 33 ? s 34 : "&#" + s.charCodeAt(0) + ";"; 35 }) 36 .replace(/</g, "<") 37 .replace(/>/g, ">"); 38 } 39 }