Skip to content

ISerializable documentation claims it works with XmlSerializer #9658

@MauNguyenVan

Description

@MauNguyenVan

Description

The documentation for ISerializable claims that this interface applies to both binary and XML serialization. In actual fact, the XML Serializer completely ignores this interface. It is actually do nothing with implement of ISerializable and may be binary serialization have the same issuse.

Reproduction Steps

Use .NET 8.0
code from ms docs

[Serializable]
public class MyObject : ISerializable
{
    public int n1;
    public int n2;
    public String str;

    public MyObject()
    {
    }

    protected MyObject(SerializationInfo info, StreamingContext context)
    {
      n1 = info.GetInt32("i");
      n2 = info.GetInt32("j");
      str = info.GetString("k");
    }

    public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("i", n1);
        info.AddValue("j", n2);
        info.AddValue("k", str);
    }
}

///in Main

            // Create an instance of your class
            MyObject obj = new MyObject() { n1=1, n2=2, str="str"};

            // XmlSerializer instance
            XmlSerializer serializer = new XmlSerializer(typeof(MyObject));

            // Serialize the object to XML
            using (TextWriter writer = new StreamWriter("serialized.xml"))
            {
                serializer.Serialize(writer, obj);
            }
            // Deserialize the object from XML
            using (XmlReader reader = XmlReader.Create("serialized.xml"))
            {
                MyObject deserializedObj = (MyObject)serializer.Deserialize(reader);

                // Use the deserialized object
                Console.WriteLine($"n1: {deserializedObj.n1}, str: {deserializedObj.str}");
            }

Expected behavior

<?xml version="1.0" encoding="utf-8"?>
<MyObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <i>1</i>
  <j>2</k>
  <k>str</k>
</MyObject>

Actual behavior

<?xml version="1.0" encoding="utf-8"?>
<MyObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <n1>1</n1>
  <n2>2</n2>
  <str>str</str>
</MyObject>

Regression?

Use .NET 8.0

Known Workarounds

No response

Configuration

No response

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Pri3Indicates issues/PRs that are low priorityarea-SerializationuntriagedNew issue has not been triaged by the area owner

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions