序列化并将数据保存到字符串

时间:2014-09-10 06:18:41

标签: c# serialization

我这里有这个代码:

public xml.Sheet Sheet1 { get; set; }

我需要能够序列化它并将内容保存在字符串中。让我们说xml1

我能够进行反序列化而不是序列化。

Sheet1具有以下属性:

Sheet1.Root
Sheet1.Controls

XML文件应为:

<Root>
<Control> </Control> 
<Control> </Control> 
<Control> </Control> 
</Root>

<Root>
<Control> </Control> 
<Control> </Control> 
<Control> </Control> 
</Root>

我该如何开始?

 XmlSerializer ser = new XmlSerializer(Sheet1.GetType());

编辑:我的新代码是这样的:

 public void GetContents(ref string xml1, ref string xml2)
        {

            using (var writer = new StringWriter())
            {
                XmlSerializer ser = new XmlSerializer(Sheet1.GetType());
                ser.Serialize(writer, Sheet1);
                xml1 = writer.ToString();
            }


            using (var writer2 = new StringWriter())
            {
                XmlSerializer ser2 = new XmlSerializer(Sheet2.GetType());
                ser2.Serialize(writer2, Sheet2);
                xml2 = writer2.ToString();

            }

        }

然后我称之为这个方法:

compare.GetContents(ref xml1, ref xml2); 

现在我获得了新的字符串,如何将它们保存到XML文件中?

1 个答案:

答案 0 :(得分:0)

您的Sheet课程需要标记为[Serializable]。另请注意,只有public属性和字段将被序列化。

string xml1;
using (var writer = new StringWriter()) 
{
  XmlSerializer ser = new XmlSerializer(Sheet1.GetType());
  ser.Serialize(writer, Sheet1);
  xml1 = writer.ToString();
}

并保存到文件中:

using (var fileWriter = new StreamWriter("filename.xml", Encoding.UTF8))
{
  fileWriter.Write(xml1);
}