UNPKG

2.36 kBPlain TextView Raw
1import {Bean} from "./context/context";
2let LINE_SEPARATOR = '\r\n';
3
4@Bean('xmlFactory')
5export class XmlFactory {
6 createXml(xmlElement: XmlElement, booleanTransformer?:(currentValue:boolean)=>string) :string{
7 let props: string = "";
8 if (xmlElement.properties) {
9 if (xmlElement.properties.prefixedAttributes) {
10 xmlElement.properties.prefixedAttributes.forEach((prefixedSet:PrefixedXmlAttributes)=>{
11 Object.keys(prefixedSet.map).forEach((key) => {
12 props += this.returnAttributeIfPopulated(prefixedSet.prefix + key, prefixedSet.map[key], booleanTransformer);
13 });
14 });
15 }
16
17 if (xmlElement.properties.rawMap) {
18 Object.keys(xmlElement.properties.rawMap).forEach((key) => {
19 props += this.returnAttributeIfPopulated(key, xmlElement.properties.rawMap[key], booleanTransformer);
20 })
21 }
22 }
23 let result: string = "<" + xmlElement.name + props;
24
25 if (!xmlElement.children && xmlElement.textNode == null) {
26 return result + "/>" + LINE_SEPARATOR
27 }
28
29 if (xmlElement.textNode != null){
30 return result + ">" + xmlElement.textNode + "</" + xmlElement.name + ">" + LINE_SEPARATOR
31 }
32
33 result += ">" + LINE_SEPARATOR;
34 xmlElement.children.forEach((it) => {
35 result += this.createXml(it, booleanTransformer);
36 });
37 return result + "</" + xmlElement.name + ">" + LINE_SEPARATOR;
38 }
39
40 private returnAttributeIfPopulated(key: string, value: any, booleanTransformer?:(currentValue:boolean)=>string) {
41 if (!value) {
42 return ""
43 }
44
45 let xmlValue: string = value;
46 if ((typeof(value) === 'boolean')) {
47 if (booleanTransformer){
48 xmlValue = booleanTransformer(value)
49 }
50 }
51
52 xmlValue = '"' + xmlValue + '"';
53
54 return " " + key + "=" + xmlValue;
55 }
56
57}
58
59
60export interface XmlElement {
61 name: string;
62 properties?: XmlAttributes;
63 children?: XmlElement[];
64 textNode?: string;
65}
66
67export interface XmlAttributes {
68 prefixedAttributes?: PrefixedXmlAttributes[];
69 rawMap?: any;
70}
71
72export interface PrefixedXmlAttributes {
73 prefix: string;
74 map: any;
75}
\No newline at end of file