0

Based on a certain flag, I need to switch between the default XmlSerialization deserializer and IXmlSerialization interface implementation. How can I do that? E.g.

  public class SomeClass: IXmlSerializer
  { 
     //Other primitive and complex properties
     //...
     // 
    
     //Another issue is - What would be the best way to inject depencencies? 
     SomeClass(ISomeDepedency dependency)
     {
     }

     public ReadXml(XmlReader rdr)
     {
       var someValues =   dependency.GetSomeValuesFromDBForCustomSerializtion();               
     }
  }

  public static void Main(string[] args)
  {
   
   //This is filled out
   XmlReader rdr = null;

    XmlSerializer serializer = new XmlSerializer(typeof(SomeClass));
    if(useCustomSerializer)
    { 
       //use IXmlSerializer implemenation
    }
   else
   {
          //use Default Serializer
   }
   var someClass= serializer.Deserialize(rdr);
  }

I know that IXmlSerializer implementation is all or nothing. Is there any way to achieve this?

ANewGuyInTown
  • 5,957
  • 5
  • 33
  • 45
  • You need three methods 1)ReadXml, WriteXml, and GetSchema. See : https://learn.microsoft.com/en-us/dotnet/api/system.xml.serialization.ixmlserializable?view=net-6.0, The read method you can create a child serizilzer : XmlSerializer serializer = new XmlSerializer(typeof(ChildClass));. Then deserialize the child with the same reader or create a new child reader. – jdweng Jul 07 '22 at 05:46
  • See my answer here : https://stackoverflow.com/questions/72843947/deserialize-xml-with-different-type-rows-c-sharp/72845615#72845615 – jdweng Jul 07 '22 at 05:50
  • I removed the other 2 for brevity. "the read method you can create....." , I have many types within the class, which would mean many switch cases. In the event someone adds a new type within the class, that needs to be part of that switch as well. – ANewGuyInTown Jul 07 '22 at 06:01
  • Does the produced XML need to fit any specific schema/format or any deserializable XML will do it? If the latter, you can try [this](https://github.com/koszeggy/KGySoft.CoreLibraries#xml-serialization) serializer (disclaimer: written by me). It respects `IXmlSerializable` implementation by default but it has an `IgnoreIXmlSerializable` serialization option. – György Kőszeg Jul 07 '22 at 08:46
  • The switch was only needed to split the row tags into two lists. I usually use Xml Linq using XElement.ReadFrom(reader). – jdweng Jul 07 '22 at 08:48
  • I don't know of any way to do this. Easiest workaround may be to create a [DTO](https://en.wikipedia.org/wiki/Data_transfer_object) and use that instead. – dbc Jul 07 '22 at 14:54
  • @GyörgyKőszeg, it's the former. Thanks for your input. – ANewGuyInTown Jul 07 '22 at 22:46

0 Answers0