Given the following XML:
<RESPONSE version="10">
<RESULTS MyAttribute="1" />
</RESPONSE>
I can deserialize this as follows:
[XmlRoot("RESPONSE")]
public class Response
{
[XmlElement(ElementName = "RESULTS")]
public Results Results {get;set;}
}
public class Results
{
[XmlAttribute(AttributeName = "MyAttribute")]
public bool MyAttribute { get; set; }
}
var serializer = new XmlSerializer(typeof(Response));
var result = (Response)serializer.Deserialize(new StringReader(xml));
It works, and everything is in order. However, the problem is that I want to deserialize the following XML, and also do not want to duplicate the Response class, I want to use a general approach.
<RESPONSE version="10">
<SOCCER AnotherAttribute="1" />
</RESPONSE>
I tried to do the following:
[XmlRoot("Response")]
public class Response<T>
{
public T Data {get;set;}
}
public class SoccerRoot
{
[XmlElement(ElementName = "SOCCER")]
public class Soccer {get;set;}
}
public class Soccer
{
[XmlAttribute(AttributeName = "AnotherAttribute")]
public bool AnotherAttribute {get;set;}
}
var serializer = new XmlSerializer(typeof(Response<SoccerRoot>));
var result = (Response<SoccerRoot>)serializer.Deserialize(new StringReader(xml));
But this does not work, I also tried to inherit the Response class, but with no luck. Im getting the following error:<xmlns='' > was not expected.
Am I really here, or is it not possible to use a general approach when deserializing XML files?
source
share