简体   繁体   English

如何将对象实例序列化为xml?

[英]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 ? 使用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. 您需要给您的Member财产设置者。 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 ? 使用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. 这是对XML序列化的一种可以理解的限制,因为没有设置器,您将无法将xml反序列化为DataClass对象。 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. 感谢@MongZhu帮助我实现了这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM