在标头中使用UTF-16读取XML时出错 [英] Error reading XML with UTF-16 in header

查看:82
本文介绍了在标头中使用UTF-16读取XML时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个读取xml文件的程序。该文件是给我的,我不创建它。



我正在使用

I have a program that reads an xml file. The file is given to me, I don't create it.

I'm using

using (XmlTextReader reader = new XmlTextReader(Filename))
         {

           while (reader.Read())





,它工作正常,除非xml文件中包含

encoding =utf-16

。在这种情况下,我得到

System.Xml.dll中出现未处理的System.Xml.XmlException类型异常

附加信息:没有Unicode字节顺序标记。无法切换到Unicode。



更改xml文件说utf-8有效,但我不想每次都要编辑文件。有没有办法在读者代码中解决这个问题?

完整的XML文件是





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 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>





我尝试了什么:



我尝试使用(XmlTextReader reader = new XmlTextReader(Filename,Encoding.GetEncoding(UTF- 8)))但如果这样可行,那么我就不会想出语法。



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.

推荐答案

尝试使用 StreamReader 作为 XmlTextReader 的来源:

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


这篇关于在标头中使用UTF-16读取XML时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆