使用UTF-8或UTF-16编码读取/写入XML文件

时间:2015-08-26 16:16:18

标签: xml encoding utf-8 vbscript

我有一个标题为<xml version="1.0" encoding="UTF-16">的XML文件。但是,在记事本编辑器中打开文件,它表示要以UTF-8编码的文件。

我有一个使用OpenTextFile方法的VBS代码来读取原始文件,向其中添加一些元素,然后将其另存为新文件。新文件未以正确的格式保存,因此在使用xmlFile.Load解析新文件时,它会出错。我尝试过不同的格式参数,似乎无法正确保存文件。知道下面有什么不对吗?

set xFso =CreateObject("Scripting.FileSystemObject") 
Set tsIn = xFso.OpenTextFile(xmlDataFile, 1, false, -2)
Set tsOut = xFso.OpenTextFile(xmlDataFile & ".new", 2, True, -2)
Do While Not tsIn.AtEndOfStream
   tsOut.WriteLine tsIn.ReadLine
Loop

'Add some more elements here and save the new file

tsIn.Close
Set tsIn = Nothing
tsOut.Close
Set tsOut = Nothing

xFso.CopyFile xmlDataFile & ".new", xmlDataFile, True
xFso.DeleteFile xmlDataFile & ".new", True

xmlData.load(xmlDataFile) 'parse error <> 0 here

1 个答案:

答案 0 :(得分:1)

您正在将UTF-8编码文件打开为UTF-16编码文件。将其转换为实际的UTF-16编码:

filename = "C:\path\to\your.xml"

Set stream = CreateObject("ADODB.Stream")
stream.Open
stream.Type = 2 'text
stream.Charset = "utf-8"
stream.LoadFromFile filename
txt = tream.ReadText
stream.Close

Set fso = CreateObject("Scripting.FileSystemObject")
fso.OpenTextFile(Filename, 2, True, -1).Write txt