XML反序列化失败 [英] XML deserialization fail
问题描述
我反序列化下面的XML文件。使用XML序列化与VSTS 2008 + C#+。NET 3.5的。
I am deserializing the following XML file. Using XML serializer with VSTS 2008 + C# + .Net 3.5.
下面是XML文件。
<?xml version="1.0" encoding="utf-8"?>
<Person><Name>=b?olu</Name></Person>
下面是屏幕快照的XML文件的XML文件和二进制格式,
Here is the screen snapshot for the display of the XML file and binary format of the XML file,
如果有一些解决办法接受这样的角色,这将是伟大的!由于我的XML文件是很大的,如果这样的角色真的是无效的,应该被过滤,我想保持反序列化后剩余的XML文件的内容。
If there are some solutions to accept such characters, it will be great! Since my XML file is big, and if such characters are really invalid and should be filtered, I want to keep remaining content of XML file after deserialization.
目前XML序列化失败,出现InvalidOperationException和整个XML文件的信息将会丢失。
Currently XML deserialization fails with InvalidOperationException and the whole XML file information will be lost.
其实,开的时候在VSTS这个XML文件中,有错误是这样,错误1字符'?',十六进制值0xFFFF在XML文档中是非法的。我很困惑,因为以二进制形式,没有0xFFFF的值。
Actually, when open this XML file in VSTS, there is error like this, Error 1 Character '?', hexadecimal value 0xffff is illegal in XML documents. I am confused since in the binary form, there is no 0xffff values.
任何解决方案或想法?
EDIT1:这里是我的code,用来反序列化XML文件,
here is my code which is used to deserialize XML file,
static void Foo()
{
XmlSerializer s = new XmlSerializer(typeof(Person));
StreamReader file = new StreamReader("bug.xml");
s.Deserialize(file);
}
public class Person
{
public string Name;
}
推荐答案
您是否尝试过DataContractSerializer的呢?我遇到了一个有趣的情况,当有人复制并粘贴一些word或excel的东西到我的web应用程序:字符串包含了一些无效的控制字符(如垂直选项卡)。令我吃惊的把它发送到一个WCF服务,甚至要求当它读回100%原装时,这是序列化。纯.NET环境没有这个问题,所以我假设的DataContractSerializer能处理这些东西(这是恕我直言违反XML规范的,不过)。
我们有访问同一个服务的另一个Java客户端 - 接收到这个纪录,当它失败...
Have you tried the DataContractSerializer instead? I've encountered an interesting situation, when someone copy and pasted some word or excel stuff into my web application: the string contained some invalid control characters (such as vertical tab). To my surprise this was serialized when sending it to a WCF service and even read back 100% original when requesting it. The pure .net environment did not have a problem with this, so I assume that the DataContractSerializer can handle such stuff (which is IMHO a violation of XML spec, however).
[之后我的评论丑陋的格式编辑下面]
We had another Java client accessing the same service - it failed when receiving this record...
试试这个:
Try this:
第二个马克的意见是关于DataContractSerializers习惯,使XmlElements而不是XMLATTRIBUTES:
DataContractSerializer serializer = new DataContractSerializer(typeof(MyType));
using (XmlWriter xmlWriter = new XmlTextWriter(filePath, Encoding.UTF8))
{
serializer.WriteObject(xmlWriter, instanceOfMyType);
}
using (XmlReader xmlReader = new XmlTextReader(filePath))
{
MyType = serializer.ReadObject(xmlReader) as MyType;
}
The comment of the second Marc is about DataContractSerializers habit to make XmlElements instead of XmlAttributes:
而不是
<AnElement AnAttribute="value" />
这篇关于XML反序列化失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!