我正在.vbs 文件中创建一个 xml 文件,其节点值如下所示,
<car>David's</car>
<company>Mannar & Co.</company>
在解析这个 xml 时,我发现 & 等问题。
我想用编码字符(带有函数或其他东西)转换所有可能的xml 特殊字符,以便在解析时得到原始内容。
感谢您。
这是一个旧帖子,但我正在回复,因为我希望这可以为某人节省一些悲伤
我正在处理一个供应商抱怨在某些情况下并非所有特殊字符都在 XML 中转义的问题。我很惊讶地看到开发人员使用了它自己的逻辑(函数)而不是框架提供的某些功能,因为转义听起来像是一项非常常见的任务。以下是修复前的功能:
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
有趣的是,它看起来完全是这篇文章的答案之一(可能是从这里复制的:-)。
我将问题追溯到特殊字符被替换的顺序。替换&符号(&
)必须是第一个替换(行),因为替换(如"
:)正在注入&符号,而&符号又将被替换&
。例如,如果我有以下字符串:We <3 SO
. 原始(上面)函数会将其转义为:We &lt;3 SO
. 正确的转义是:We <3 SO
.
所以修改后的函数可以是:
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
为了完整起见,您可以在此处找到 XML 中的预定义实体
根据我自己制作的 OP 的评论,我找不到可靠的版本,我认为它涵盖了所有可能的 ascii 字符
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), "&")
tmp = Replace(tmp, chr(32), " ")
HTML_Encode = tmp
End Function
Function HTML_Decode(byVal encodedstring)
Dim tmp, i
tmp = encodedstring
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) )
tmp = Replace(tmp, " ", 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 !@#&#177; is a & test!
wscript.echo HTML_Decode(HTML_Encode(str)) '=> This !@#± is a & test!
当我找到另一个钥匙时,我的钥匙还不冷,我把它作为另一个答案,因为输出非常不同,所以你可以选择最适合的。我确实删除了原始答案以免混淆
Function Escape(s)
Dim scr
Set scr = CreateObject("MSScriptControl.ScriptControl")
scr.Language = "VBScript"
scr.Reset
Escape = scr.Eval("escape(""" & s & """)")
End Function
Function Unescape(s)
Dim scr
Set scr = CreateObject("MSScriptControl.ScriptControl")
scr.Language = "VBScript"
scr.Reset
Unescape = scr.Eval("unescape(""" & s & """)")
End Function
wscript.echo Escape("This !@#± is a & test!") '=> This%20%21@%23%B1%20is%20a%20%26%20test%21
wscript.echo Unescape(Escape("This !@#± is a & test!")) '=> This !@#± is a & test!