c# - 系统.InvalidOperationException : < xmlns ='' > was not expected

标签 c# .net xml deserialization

<分区>

我在反序列化 XML 文档时遇到问题。它给了我:

There is an error in XML document (1, 23). ---> System.InvalidOperationException: was not expected.

这是我的 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();
        }
    }
}

最佳答案

我有一个类似的问题,这对我有用 - 尝试将根属性的名称添加到 XmlSerializer 对象,看看是否有帮助。

MyApp ma = MyApp.Deserialize(strXml);

public static MyApp Deserialize(string xml) {
    System.IO.StringReader stringReader = null;
    try {
      stringReader = new System.IO.StringReader(xml);

      var xmlSerializer = 
          new XmlSerializer(MyApp.GetType(), new XmlRootAttribute("car");

        var myApp = xmlSerializer.Deserialize(stringReader) as MyApp;

        return myApp;
      } finally {
        if ((stringReader != null)) {
          stringReader.Dispose();
        }
      }
    }

关于c# - 系统.InvalidOperationException : < xmlns ='' > was not expected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28960736/

相关文章:

.net - 将 pdf 转换为 Word 文档

c# - 将多边形切成 n block

xml - 将节点导入到另一个XML文档

c# - 我可以要求 child 初始化在其父类中声明的变量吗?

c# - C# 会内联这些函数吗?

c# - WPF 模态窗口作为 WinForms 中的工具窗口消失

javascript - 由于某种原因,jQuery 中的 .text() 方法不适用于 xml 元素

java.lang.ClassCastException,无法转换 DeepNodeListImpl

C# 验证字段的更好方法。 (Linq 到 SQL)

c# - 使用 jquery 或 javascript 从 asp.net 转发器隐藏/显示特定数量的项目