0

I have an XML file with header <xml version="1.0" encoding="UTF-16">. However, opening the file in notepad editor, it indicates the file to be encoded in UTF-8.

I have a VBS code using the OpenTextFile method to read the original file, add some elements to it and then save it as a new file. The new file is not saved in the correct format and hence when using xmlFile.Load to parse the new file, it errors out. I have tried different format parameters and do not seem to be able to save the file correctly. Any idea what is incorrect below?

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
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
amindomeniko
  • 417
  • 6
  • 23

1 Answers1

1

You're opening a UTF-8 encoded file as a UTF-16 encoded file. Convert it to actual UTF-16 encoding:

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
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328