C# 尝试反序列化 xml 文件时出现异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/673468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Exception when trying to deserialize a xml file
提问by CruelIO
Im trying to deserialize an XML file with XmlSerializer, however im getting this exception:
我试图用 XmlSerializer 反序列化一个 XML 文件,但是我收到了这个异常:
"There is an error in XML document (1, 2)" The innerexception is: "
<Mymessage xmlns='http://MyMessages/'>
was not expected."
“XML 文档中存在错误 (1, 2)” 内部异常是:“
<Mymessage xmlns='http://MyMessages/'>
不是预期的”。
Which is the very first line in the XML file. my guess is that it has something to do with the xmlns.
这是 XML 文件中的第一行。我的猜测是它与xmlns有关。
I tried to ask Google, and then tried to add the following line to my code
我试着问谷歌,然后尝试将以下行添加到我的代码中
[XmlRoot("MyMessage", Namespace="'http://MyMessages/")]
But I still get the same exception.
但我仍然得到同样的例外。
采纳答案by CruelIO
In the constructor of the XmlSerializer i needed to specify a default namespace, after doing that everything worked just fine
在 XmlSerializer 的构造函数中,我需要指定一个默认命名空间,之后一切正常
回答by Binoj Antony
Please provide the full XML file code to help understand the issue better.
请提供完整的 XML 文件代码以帮助更好地理解问题。
Also put this as the first line in the xml file and see if this solves the issue
也把它作为 xml 文件的第一行,看看这是否解决了问题
<?xml version="1.0" encoding="utf-8"?>
回答by Marc Gravell
It sounds like you have a borked xml file. Easy ways to find out:
听起来您有一个无聊的 xml 文件。简单的查找方法:
- try loading it into an xml viewer
- or just make sure it has a .xml extension and load in VS or IE
- or run xsd.exe over it
- 尝试将其加载到 xml 查看器中
- 或者只是确保它有一个 .xml 扩展名并在 VS 或 IE 中加载
- 或者在它上面运行 xsd.exe
If they complain, then the xml is certainly corrupt. If they work fine, and display your data, then you probably have the serialization attributes wrong. Try using xsd.exe with the "/classes" switch to see what it would do with it...
如果他们抱怨,那么 xml 肯定已损坏。如果它们工作正常并显示您的数据,那么您的序列化属性可能有误。尝试将 xsd.exe 与“/classes”开关一起使用,看看它会用它做什么...
回答by timdougall
Further to CruelIO's response, I resolved the error by adding:
继 CruelIO 的回应之后,我通过添加以下内容解决了错误:
[XmlRoot("RenderResult", Namespace = "http://mynamespace.uri.org")]
to the class that I was trying to deserialize. e.g: the serialization code was:
到我试图反序列化的班级。例如:序列化代码是:
RenderResult result;
using (var memoryStream = new MemoryStream(data))
{
var xmlSerializer = new XmlSerializer(typeof(RenderResult));
result = (RenderResult)xmlSerializer.Deserialize(memoryStream);
}
and my class looked like this:
我的班级看起来像这样:
[XmlRoot("RenderResult", Namespace = "http://mynamespace.uri.org")]
public class RenderResult
{
}