Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vbscript create-convert xml with special characters

Tags:

xml

vbscript

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.

like image 940
itsraja Avatar asked Aug 19 '26 19:08

itsraja


1 Answers

This is an old post but I am replying as I hope this will save someone some grief

I was working on an issue where a vendor complained that in some cases not all the special characters are being escaped in the XML. I was surprised to see that the dev used it’s own logic (function) and not some functionality offered by the framework as escaping sounds like a very common task. The following is the function before the fix:

Function HTML_Encode(byVal string)
  Dim tmp, i 
  tmp = string
  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(38), "&amp;") <- the problem: this line should be the first replacement
  tmp = Replace(tmp, chr(32), "&nbsp;")
  HTML_Encode = tmp
End Function

Funny enough, it looks exactly as one of the answers to this post (probably copied from here :-).

I traced the problem to the order which the special characters is being replaced. Replacing the ampersand (&) MUST be the first replacement (line) as replacements (like: &quot;) are injecting ampersands which in turn will be replaced by &amp;. For example, if I have the following string: We <3 SO. The original (above) function will escape it to: We &amp;lt;3 SO. The right escaping is: We &lt;3 SO.

So the revised function can be:

  Function HTML_Encode(byVal string)
      Dim tmp, i 
      tmp = string

      tmp = Replace(tmp, chr(38), "&amp;") <- Must be the first replacement (Thanks Aaron)

      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

For completeness, you can find the Predefined entities in XML here

like image 145
Rotem Varon Avatar answered Aug 22 '26 14:08

Rotem Varon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!