XmlElem.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import type { NamespaceTable } from "@/ua/NameSpaceTable";
  2. export class XMLElem {
  3. name: string;
  4. value: string;
  5. elements: XMLElem[]=[];
  6. attributes: XmlAttr[]=[];
  7. constructor(name: string, value?:string) {
  8. this.name=name;
  9. this.value=value||'';
  10. }
  11. public add(elem: XMLElem): XMLElem {
  12. this.elements.push(elem);
  13. return elem;
  14. }
  15. public attr(name:string, value: string|boolean|undefined|null): XMLElem {
  16. if(value===undefined||value===null)
  17. return this; //skip undefined/null values
  18. this.attributes.push(new XmlAttr(name, value?.toString()));
  19. return this;
  20. }
  21. public elem(name:string, value: XMLElem|string|boolean|undefined|null): XMLElem {
  22. if(value===undefined||value===null)
  23. return this; //skip undefined/null values
  24. if(value instanceof XMLElem)
  25. this.elements.push(value);
  26. this.elements.push(new XMLElem(name, value?.toString()));
  27. return this;
  28. }
  29. public toString(level: number=0): string {
  30. let s="";
  31. if(level==0) {
  32. s+='<?xml version="1.0" encoding="utf-8" ?>\n'
  33. }
  34. s+=" ".repeat(level+1) + `<${this.name} `;
  35. for(const attr of this.attributes) {
  36. if(attr.value==undefined)
  37. continue;
  38. s+=`${attr.name}="${this.escapeXml(attr.value)}" `;
  39. }
  40. s=s.slice(0, -1);
  41. s+=`>`
  42. for(const elem of this.elements) {
  43. s+="\n"+" ".repeat(level) + elem.toString(level+1);
  44. }
  45. if(this.value && this.elements.length==0) {
  46. s+=this.escapeXml(this.value);
  47. }
  48. if(this.elements.length>0)
  49. s+="\n" + " ".repeat(level);
  50. s+=`</${this.name}>`
  51. return s;
  52. }
  53. private escapeXml(unsafe: string) {
  54. return unsafe.replace(/[<>&'"]/g, (c: string):string => {
  55. switch (c) {
  56. case '<': return '&lt;';
  57. case '>': return '&gt;';
  58. case '&': return '&amp;';
  59. case '\'': return '&apos;';
  60. case '"': return '&quot;';
  61. }
  62. return c;
  63. });
  64. }
  65. }
  66. class XmlAttr {
  67. constructor(public name: string,
  68. public value: string) {
  69. }
  70. }
  71. export interface IToXML {
  72. toXML(lnst: NamespaceTable, gnst: NamespaceTable) :XMLElem;
  73. }