Pittfall
Pittfall

Reputation: 2851

How do I serialize instance of object to xml?

Here is my code:

public class DataClass
{
   private string member = string.Empty;
   public string Member
   {
      get
      {
         return member;
      }
   }

   private DataClass() { }
   public DataClass(string memberToSet) 
   {
      this.member = memberToSet;
   }

   public string SerializeXML()
   {
      XmlSerializer xsSubmit = new XmlSerializer(this.GetType());

      var xml = "";

      using (var sww = new StringWriter())
      {
         using (XmlWriter writer = XmlWriter.Create(sww))
         {
            xsSubmit.Serialize(writer, this);
            xml = sww.ToString(); // Your XML
         }
      }

      return xml;
   }
}

I've done this with an external method and it works. Is there some restriction to using this? Here is my result which does not serialize any properties in my object.

<?xml version="1.0" encoding="utf-16"?><DataClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />

Upvotes: 1

Views: 89

Answers (2)

Pittfall
Pittfall

Reputation: 2851

This is not possible with a private setter. It is an understandable restriction to XML serialization as you will not be able to deserialize xml to a DataClass object without a setter. The reason for the design rather than using something like a copy constructor, is because the deserialize process copies one member at a time. If it tried to hold all of the data and use a copy constructor, it could potentially need to hold some huge object in memory.

Credit to @MongZhu for helping me realize this.

Upvotes: 1

Mong Zhu
Mong Zhu

Reputation: 23732

You need to give your Member property a setter. Try this :

public class DataClass
{
    public string Member { get; set; }

    public DataClass(string memberToSet)
    {
        this.Member = memberToSet;
    }
...

And your result will look like this:

<?xml version="1.0" encoding="utf-16"?><DataClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema"><Member>asd</Member></DataClass>

Is there some restriction to using this?

not that I know of. It depends more on the accessibility of properties

Upvotes: 1

Related Questions