Click here to Skip to main content
15,885,309 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a program that reads an xml file. The file is given to me, I don't create it.

I'm using
C#
using (XmlTextReader reader = new XmlTextReader(Filename))
         {

           while (reader.Read())


and it works fine unless the xml file has
encoding="utf-16"
in it. In that case I get
An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll
Additional information: There is no Unicode byte order mark. Cannot switch to Unicode.

changing the xml file to say utf-8 works, but I don't want to have to edit the file every time. Is there a way to fix this in the reader code?
the complete XML file is

XML
<?xml version="1.0" encoding="utf-16"?>
<LapSyncData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <DriverData>
    <Driver position="1" name="Bob Smith (1)" carNum="4" laps="4" lapTime="13.88" elapsedTime="55.52" pace="50.00" fastLap="10.83" fastLapOn="3" avgLap="12.50" done="True" DriverID="8b8f1514-75d6-4aaf-b537-fe005d3b16b4" />
  </DriverData>
  <RaceData>
    <Race Version="0.1" className="4S" classID="4ab689ac-67e2-4cdb-bf9a-a0109b8bc7e8" raceStatus="complete" raceLength="4" timeElapsed="58" timeRemaining="0" raceNumber="1" totalRaces="5" round="1" />
  </RaceData>
</LapSyncData>


What I have tried:

I tried using (XmlTextReader reader = new XmlTextReader(Filename, Encoding.GetEncoding("UTF-8"))) but if that will work then I coudn't figure out teh syntax.
Posted
Updated 10-Aug-16 6:04am
Comments
Kenneth Haugland 10-Aug-16 11:44am    
Perhaps:
http://stackoverflow.com/questions/4520184/how-to-detect-the-character-encoding-of-a-text-file
[no name] 10-Aug-16 11:48am    
The XML file does not contain the ByteOrderMark (BOM). For a test, open the file with Notepad and save it as Unicode. Notepad will insert the BOM at the begining of the file.

1 solution

Try using a StreamReader as the source for your XmlTextReader:
C#
using (TextReader file = File.OpenText(Filename))
using (XmlReader reader = XmlReader.Create(file))
{
    ...
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900