@@ -24,6 +24,17 @@ function handleAttributes(obj: any): any {
2424 return obj
2525}
2626
27+ function escapeXml ( text : string ) {
28+ if ( text == null ) return ''
29+ return text
30+ . toString ( )
31+ . replace ( / & / g, '&' )
32+ . replace ( / < / g, '<' )
33+ . replace ( / > / g, '>' )
34+ . replace ( / " / g, '"' )
35+ . replace ( / ' / g, ''' )
36+ }
37+
2738function getAttributes ( obj : any ) {
2839 let tmp = obj
2940 try {
@@ -33,7 +44,7 @@ function getAttributes(obj: any) {
3344 } catch ( error ) {
3445 tmp = JSON . stringify ( handleAttributes ( obj ) ) . replace ( / " / g, "'" )
3546 }
36- return tmp
47+ return escapeXml ( String ( tmp ) )
3748}
3849
3950const tn = '\t\n'
@@ -44,8 +55,11 @@ function toXml(obj: any, name: string, depth: number) {
4455 let str = ''
4556 const prefix = tn + frontSpace
4657 if ( name === '-json' ) return ''
58+ if ( obj !== 0 && obj !== false && ! obj ) {
59+ return `${ prefix } <${ name } />`
60+ }
4761 if ( name === '#text' ) {
48- return prefix + obj
62+ return prefix + escapeXml ( String ( obj ) )
4963 }
5064 if ( name === '#cdata-section' ) {
5165 return `${ prefix } <![CDATA[${ obj } ]]>`
@@ -74,7 +88,7 @@ function toXml(obj: any, name: string, depth: number) {
7488 str +=
7589 attributes + ( children !== '' ? `>${ children } ${ prefix } </${ name } >` : ' />' )
7690 } else {
77- str += `${ prefix } <${ name } >${ obj . toString ( ) } </${ name } >`
91+ str += `${ prefix } <${ name } >${ escapeXml ( String ( obj ) ) } </${ name } >`
7892 }
7993
8094 return str
@@ -88,4 +102,4 @@ function lfJson2Xml(obj: any) {
88102 return xmlStr
89103}
90104
91- export { lfJson2Xml , handleAttributes }
105+ export { lfJson2Xml , handleAttributes , escapeXml }
0 commit comments