Mxl.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { IXmlElement } from "./Xml";
  2. import { Promise } from "es6-promise";
  3. import JSZip = require("jszip");
  4. /**
  5. * Some helper methods to handle MXL files.
  6. */
  7. export class MXLHelper {
  8. /**
  9. *
  10. * @param data
  11. * @returns {Promise<IXmlElement>}
  12. * @constructor
  13. */
  14. public static MXLtoIXmlElement(data: string): Promise<IXmlElement> {
  15. const zip: JSZip.JSZip = new JSZip();
  16. // asynchronously load zip file and process it - with Promises
  17. return zip.loadAsync(data).then(
  18. (_: any) => {
  19. return zip.file("META-INF/container.xml").async("string");
  20. },
  21. (err: any) => {
  22. throw err;
  23. }
  24. ).then(
  25. (content: string) => {
  26. const parser: DOMParser = new DOMParser();
  27. const doc: Document = parser.parseFromString(content, "text/xml");
  28. const rootFile: string = doc.getElementsByTagName("rootfile")[0].getAttribute("full-path");
  29. return zip.file(rootFile).async("string");
  30. },
  31. (err: any) => {
  32. throw err;
  33. }
  34. ).then(
  35. (content: string) => {
  36. const parser: DOMParser = new DOMParser();
  37. const xml: Document = parser.parseFromString(content, "text/xml");
  38. const doc: IXmlElement = new IXmlElement(xml.documentElement);
  39. return Promise.resolve(doc);
  40. },
  41. (err: any) => {
  42. throw err;
  43. }
  44. ).then(
  45. (content: IXmlElement) => {
  46. return content;
  47. },
  48. (err: any) => {
  49. throw new Error("extractSheetFromMxl: " + err.message);
  50. }
  51. );
  52. }
  53. public static MXLtoXMLstring(data: string): Promise<string> {
  54. const zip: JSZip.JSZip = new JSZip();
  55. // asynchronously load zip file and process it - with Promises
  56. return zip.loadAsync(data).then(
  57. (_: any) => {
  58. return zip.file("META-INF/container.xml").async("string");
  59. },
  60. (err: any) => {
  61. throw err;
  62. }
  63. ).then(
  64. (content: string) => {
  65. const parser: DOMParser = new DOMParser();
  66. const doc: Document = parser.parseFromString(content, "text/xml");
  67. const rootFile: string = doc.getElementsByTagName("rootfile")[0].getAttribute("full-path");
  68. return zip.file(rootFile).async("string");
  69. },
  70. (err: any) => {
  71. throw err;
  72. }
  73. );
  74. }
  75. }