简体   繁体   中英

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" />

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

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.

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