Search code examples
c#xmlhttpxml-deserialization

Deserialize XML HTTP Response with C#


I am trying to write a serialization class, so that it would deserialize the http response from a camera device, however I and getting hung up on excluding the xsi:noNamespaceSchemaLocation tag. The deserialization fails with "xsi" is an undeclared prefix error message.

XML Http Response:

<root xsi:noNamespaceSchemaLocation='http://www.example.com/vapix/http_cgi/recording/stop1.xsd'><stop recordingid='20161125_121817_831B_ACCC8E627419' result='OK'/></root>

C# code:

try
{
  StopRecord ListOfStops = null;
  XmlSerializer deserializer = new XmlSerializer(typeof(StopRecord));
  using (XmlTextReader reader = new XmlTextReader(new StringReader(httpResponse)))
  {
   ListOfStops = deserializer.Deserialize(reader) as StopRecord ;
  }
}
catch (Exception ex)
{
   Console.WriteLine(ex.InnerException);
}

C# Serialization Class:

public class StopRecord
{
   [Serializable()]
   [System.Xml.Serialization.XmlRoot("root")]
   public class Root
   {
     public class stop
     {
       public stop(){}
       [System.Xml.Serialization.XmlAttribute("recordingid")]
       public string recordingid {get;set;}

       [System.Xml.Serialization.XmlAttribute("result")]
       public string result {get;set;}
     }
   }
}

Updated: Changed XmlElements to XmlAttributes. The problem with xsi still exists.


Solution

  • Just wrap this xml response with a new root element where the xsi namespace is defined:

    <wrapper xmlns:xsi='http://www.example.com'>
        <!-- original response goes here -->
        <root xsi:noNamespaceSchemaLocation='http://www.example.com/vapix/http_cgi/recording/stop1.xsd'>
            <stop recordingid='20161125_121817_831B_ACCC8E627419' result='OK'/>
        </root>
    </wrapper>
    

    You also need to change your classes to add the Wrapper class - working example on .NET Fiddle:

    [Serializable]
    [XmlRoot("wrapper")]
    public class StopRecord
    {
        [XmlElement("root")]
        public Root Root { get; set; }
    }
    
    public class Root
    {
        [XmlElement("stop")]
        public Stop stop { get; set; }
    }
    
    public class Stop
    {
        [XmlAttribute("recordingid")]
        public string recordingid { get; set; }
    
        [XmlAttribute("result")]
        public string result { get; set; }
    }
    

    There is no need to deserialize noNamspaceSchemaLocation attritbute.