xml.ts 959 B

12345678910111213141516171819202122232425262728293031323334353637
  1. // Copyright (c) Microsoft Corporation. All rights reserved.
  2. // Licensed under the MIT License. See License.txt in the project root for license information.
  3. import * as xml2js from "xml2js";
  4. export function stringifyXML(obj: any, opts?: { rootName?: string }) {
  5. const builder = new xml2js.Builder({
  6. explicitArray: false,
  7. explicitCharkey: false,
  8. rootName: (opts || {}).rootName,
  9. renderOpts: {
  10. pretty: false
  11. }
  12. });
  13. return builder.buildObject(obj);
  14. }
  15. export function parseXML(str: string): Promise<any> {
  16. const xmlParser = new xml2js.Parser({
  17. explicitArray: false,
  18. explicitCharkey: false,
  19. explicitRoot: false
  20. });
  21. return new Promise((resolve, reject) => {
  22. if (!str) {
  23. reject(new Error("Document is empty"));
  24. } else {
  25. xmlParser.parseString(str, (err?: Error, res?: any) => {
  26. if (err) {
  27. reject(err);
  28. } else {
  29. resolve(res);
  30. }
  31. });
  32. }
  33. });
  34. }