XmlWriter.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. type XmlTagAttributes = {
  2. [key: string]: string;
  3. };
  4. /**
  5. * Simple XML writer tool.
  6. * TODO: tag names, attribute names/values validation
  7. */
  8. class XmlWriter {
  9. private content: string;
  10. private tagsStack: string[];
  11. public constructor() {
  12. this.content = '<?xml version="1.0" encoding="UTF-8"?>\n';
  13. this.tagsStack = [];
  14. }
  15. private attributesToString(attributes: XmlTagAttributes): string {
  16. const attr: string[] = [];
  17. for(const k of Object.keys(attributes)) {
  18. attr.push(`${k}="${attributes[k]}"`);
  19. }
  20. return attr.length > 0 ? ' ' + attr.join(' ') : '';
  21. }
  22. private tabs(add?: number): string {
  23. const tabsCount = this.tagsStack.length + (add ? add : 0) - 1;
  24. let tabs = '';
  25. for(let i = 0; i < tabsCount; i++)
  26. tabs += '\t';
  27. return tabs;
  28. }
  29. public startTag(tagName: string, attributes: XmlTagAttributes): XmlWriter {
  30. this.tagsStack.push(tagName);
  31. this.content += `${this.tabs()}<${tagName}${this.attributesToString(attributes)}>\n`;
  32. return this;
  33. }
  34. public endTag(): XmlWriter {
  35. if(this.tagsStack.length === 0)
  36. throw 'XmlWriter.endTag(): there is no opened tag';
  37. const tagName = this.tagsStack.pop();
  38. this.content += `${this.tabs(1)}</${tagName}>\n`;
  39. return this;
  40. }
  41. public writeText(text: string): XmlWriter {
  42. this.content += `${this.tabs(1)}<![CDATA[${text}]]>\n`;
  43. return this;
  44. }
  45. public writeTag(tagName: string, attributes: XmlTagAttributes, content: string): XmlWriter {
  46. this.startTag(tagName, attributes);
  47. this.writeText(content);
  48. this.endTag();
  49. return this;
  50. }
  51. public toString(): string {
  52. if(this.tagsStack.length > 0)
  53. throw 'XmlWriter.toString(): invalid xml (some tags are not closed properly)';
  54. return this.content;
  55. }
  56. }
  57. export default XmlWriter;