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.
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), """)
tmp = Replace(tmp, chr(39), "'")
tmp = Replace(tmp, chr(60), "<")
tmp = Replace(tmp, chr(62), ">")
tmp = Replace(tmp, chr(38), "&") <- the problem: this line should be the first replacement
tmp = Replace(tmp, chr(32), " ")
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: ") are injecting ampersands which in turn will be replaced by &. For example, if I have the following string: We <3 SO. The original (above) function will escape it to: We &lt;3 SO. The right escaping is: We <3 SO.
So the revised function can be:
Function HTML_Encode(byVal string)
Dim tmp, i
tmp = string
tmp = Replace(tmp, chr(38), "&") <- Must be the first replacement (Thanks Aaron)
For i = 160 to 255
tmp = Replace(tmp, chr(i), "&#" & i & ";")
Next
tmp = Replace(tmp, chr(34), """)
tmp = Replace(tmp, chr(39), "'")
tmp = Replace(tmp, chr(60), "<")
tmp = Replace(tmp, chr(62), ">")
tmp = Replace(tmp, chr(32), " ")
HTML_Encode = tmp
End Function
For completeness, you can find the Predefined entities in XML here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With