【发布时间】:2015-03-10 10:01:42
【问题描述】:
我在反序列化 XML 文档时遇到问题。它给了我:
XML 文档 (1, 23) 中存在错误。 ---> System.InvalidOperationException: 不是预期的。
这是我的 XML:
<?xml version="1.0" ?>
<car>
<msg>asdfgg</msg>
<userGUID>234234</userGUID>
<event>vfrewvwev</event>
</car>
这是我生成的类:
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.37595")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class car: System.ComponentModel.INotifyPropertyChanged {...
这是我使用的反序列化方法:
MyApp ma = MyApp.Deserialize(strXml);
public static MyApp Deserialize(string xml)
{
System.IO.StringReader stringReader = null;
try
{
stringReader = new System.IO.StringReader(xml);
return ((MyApp)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
}
finally
{
if ((stringReader != null))
{
stringReader.Dispose();
}
}
}
【问题讨论】:
-
不,不是我已经看到了所有其他可能的重复项
-
我不相信你。我只是按照那个答案的解决方案,它工作得很好:i.imgur.com/X6StSFY.png。即使我的类不是由 Xsd2Code 生成的,如果您只是修复 XmlRootAttribute 以包含 ElementName,它应该仍然可以工作。
-
@V.G.如果您尝试反序列化指定的 xml,为什么要转换为 MyApp 类而不是 car 类
-
就我而言,这是因为
XmlSerializer的错误声明。所以也要检查一下。
标签: c# .net xml deserialization