System.InvalidOperationException:<的xmlns = '' >没想到

时间:2015-03-10 10:01:42

标签: c# .net xml deserialization

我在反序列化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();
        }
    }
}

1 个答案:

答案 0 :(得分:7)

我遇到了类似的问题,这对我有用 - 尝试将root属性的名称添加到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();
        }
      }
    }
相关问题