Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.InvalidOperationException: < xmlns=''> was not expected [duplicate]

I have a problem deserializing an XML document. It gives me:

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

Here is my XML:

<?xml version="1.0" ?> 
<car>
    <msg>asdfgg</msg> 
    <userGUID>234234</userGUID> 
    <event>vfrewvwev</event> 
</car>

This is my generated class:

[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 {...

and this is the deserialization method im using:

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();
        }
    }
}
like image 842
v.g. Avatar asked Dec 24 '22 22:12

v.g.


1 Answers

I had a similar issue and this worked for me - try adding the name of the root attribute to the XmlSerializer object and see if that helps.

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();
        }
      }
    }
like image 152
Alex Hopkins Avatar answered Jan 01 '23 03:01

Alex Hopkins