简体   繁体   中英

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.

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 .

Appearantly, you can view or download the code for the System.Xml part of the .NET framework. This lets you look in the source code to determine when it returns null.

For the future i answer this, Use IsNullable attribute for those property can be null https://learn.microsoft.com/en-us/do.net/api/system.xml.serialization.xmlelementattribute.isnullable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM