Search code examples
xmlvbscript

vbscript create-convert xml with special characters


I'm creating a xml file in a .vbs file with node values like the following,

  <car>David's</car>
  <company>Mannar & Co.</company>

While parsing this xml, I find issues with &, etc.

I want to convert all possible xml special characters with encoded characters(with a function or something) so that while parsing I get the original content.

Thanking you.


Solution

  • Based on the comment of OP here i version i made myself, couldn't find a reliable one, i think it covers all possible ascii characters

    Function HTML_Encode(byVal string)
      Dim tmp, i 
      tmp = string
    
      tmp = Replace(tmp, chr(38), "&amp;") ' Must be the first replacement
    
      For i = 160 to 255
        tmp = Replace(tmp, chr(i), "&#" & i & ";")
      Next
      tmp = Replace(tmp, chr(34), "&quot;")
      tmp = Replace(tmp, chr(39), "&apos;")
      tmp = Replace(tmp, chr(60), "&lt;")
      tmp = Replace(tmp, chr(62), "&gt;")
      tmp = Replace(tmp, chr(32), "&nbsp;")
      HTML_Encode = tmp
    End Function
    
    Function HTML_Decode(byVal encodedstring)
      Dim tmp, i
      tmp = encodedstring
      tmp = Replace(tmp, "&quot;", chr(34) )
      tmp = Replace(tmp, "&apos;", chr(39))
      tmp = Replace(tmp, "&lt;"  , chr(60) )
      tmp = Replace(tmp, "&gt;"  , chr(62) )
      tmp = Replace(tmp, "&amp;" , chr(38) )
      tmp = Replace(tmp, "&nbsp;", chr(32) )
      For i = 160 to 255
        tmp = Replace(tmp, "&#" & i & ";", chr(i))
      Next
      HTML_Decode = tmp
    End Function
    
    str = "This !@#± is a & test!"
    wscript.echo HTML_Encode(str) '=> This&nbsp;!@#&amp;#177;&nbsp;is&nbsp;a&nbsp;&amp;&nbsp;test!
    wscript.echo HTML_Decode(HTML_Encode(str)) '=> This !@#± is a & test!