解决vb中读取xml乱码的问题(针对两种不同编码)
乱码主要有两种,若源xml编码为gb2312,使用以下方式解决乱码:
strGood= StrConv(StrBad, vbUnicode)
======================================================
若源xml编码为utf-8,使用以下方式解决乱码:
建立模块并写入以下代码:
Option Explicit
Private Declare Function MultiByteToWideChar Lib "kernel32" (ByVal CodePage As Long, ByVal dwFlags As Long, ByRef lpMultiByteStr As Any, ByVal cchMultiByte As Long, ByVal lpWideCharStr As Long, ByVal cchWideChar As Long) As Long
Private Const CP_UTF8 = 65001
'功能: 把Utf8字符转化成ANSI字符
Public Function UTF8_Decode(strString As String) As String
Dim sUTF8 As String
Dim lngUtf8Size As Long
Dim strBuffer As String
Dim lngBufferSize As Long
Dim lngResult As Long
Dim bytUtf8() As Byte
Dim n As Long
sUTF8 = strString
If LenB(sUTF8) = 0 Then Exit Function
On Error GoTo EndFunction
bytUtf8 = sUTF8
lngUtf8Size = UBound(bytUtf8) + 1
lngBufferSize = lngUtf8Size * 2
strBuffer = String$(lngBufferSize, vbNullChar)
lngResult = MultiByteToWideChar(CP_UTF8, 0, bytUtf8(0), lngUtf8Size, StrPtr(strBuffer), lngBufferSize)
If lngResult Then
UTF8_Decode = Left(strBuffer, lngResult)
End If
EndFunction:
End Function
然后再需要转码的地方使用以下代码:
strGood=UTF8_Decode(strBad)
评论