Search code examples
c#xmlxml-serialization

What's correct way to use default constructor for XmlSerializer?


Could you help me to find an error please? I'm trying to use XmlSerialize:

public static void ProcessLines(List<string> allLines, out pfm pfm)
    {
        ...
        pfm = newPfm;
        pfm forseril = new pfm("");
        XmlSerializer mySerializer = new XmlSerializer(typeof(pfm));
        StreamWriter myWriter = new StreamWriter("myFileName.xml");
        mySerializer.Serialize(myWriter, forseril);
        myWriter.Close();

    }

And here is that thing that I think should be a default constructor:

 [Serializable]
    [XmlRoot(ElementName = "Pfm", Namespace = null)]
    public class pfm
    {

        public pfm(string data)
        {
            this.data = data;
        }

        public string data;

        public Ctl ctl
        {
            get;
            set;
        }

        [XmlAttribute(AttributeName = "Name")]
        public string Name
        {
            get;
            set;
        }

    }

I used an istruction from Microsoft site: instruction


Solution

  • What XmlSerializer requires is a parameterless constructor -- a constructor with no arguments. Thus your pfm needs a constructor as follows:

    public class pfm
    {
        pfm() : this("") { }
    
        public pfm(string data)
        {
            this.data = data;
        }
    }
    

    It doesn't need to be public. Sample fiddle.