Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can XmlSerializer.Deserialize ever return null?

I ve been trying in a few different ways to get XmlSerializer.Deserialize to return null however it doesnt seem possible

I tried with a class being null, malformated xml, well formatted xml .

I might be missing something obvious here, but is it possible ?

Just to clarify give a Class MyClass that is serializable I want a similar test to the following to pass

[Fact] //this is a the test attribute when using xUnit
public void When_xml_Something_Then_serialize_returns_null()
{
    string serializedObject = "<?xml version=\"1.0\" encoding=\"utf-8\"?><MyClass xmlns:xsi=\"http://www.w3asdsadasdasd.org/2001/XMLSchema-instance\"></MyClass>";
    using (var stringReader = new StringReader(serializedObject))
    {
        Assert.Null(new XmlSerializer(typeof(MyClass)).Deserialize(stringReader));
    }
}

Tried different things in the serialized string, and i either get an exception or an empty instance of MyClass :( Thanks NOTE: there was a typo in this question, it is now corrected

NOTE 2: for a more detailed answer look at the comments.

like image 688
roundcrisis Avatar asked Dec 22 '22 23:12

roundcrisis


1 Answers

Yes, Deserialize can return null when the input does not contain the XML that is expected. This is frequently seen when there is confusion of the XML namespaces. If the input contains a root element with the expected name, but in a different namespace, then null will be returned.

This is often seen when dealing with ASMX web services or with Web References, especially web references against RPC-style services, where the messages are described in terms of the XSD type of the message, and not in terms of the element.

like image 114
John Saunders Avatar answered Feb 14 '23 16:02

John Saunders