具有嵌套类的多根XML

时间:2018-11-28 07:53:30

标签: c# xml xmlserializer

我有一个这样的班级:

public class Response
{
    public String AdditionalData = "";

    public Boolean Success = false;

    public int ErrorCode = 0;

    public int WarningCode = 0;

    public Transaction TransactionInfo = null;

    public PosInfo PosInformation = null;
}

,我可以成功序列化它。但是当我将该类序列化2次并将其保存在XML文件中时,XML编辑器中会出现多根错误。我知道它需要一个XML元素作为根来包围其他标签,但是我不知道如何在序列化代码中添加根元素。 消毒器类别如下:

public class Serializer
{
   public void XMLSerializer(Response response)
    {
        string path = "D:/Serialization.xml";
        FileStream fs;
        XmlSerializer xs = new XmlSerializer(typeof(Response));
        if(!File.Exists(path))
        {
            fs = new FileStream(path, FileMode.OpenOrCreate);
        }
        else
        {
            fs = new FileStream(path, FileMode.Append);
        }
        StreamWriter sw = new StreamWriter(fs);
        XmlTextWriter xw = new XmlTextWriter(sw);
        xw.Formatting = System.Xml.Formatting.Indented;
        xs.Serialize(xw, response);
        xw.Flush();
        fs.Close();
    }
}

1 个答案:

答案 0 :(得分:1)

我建议您改进代码,以至少处理可弃资源。

  

使用声明

     

提供一种方便的语法,以确保IDisposable对象的正确使用。

public class Serializer
{
    public void XMLSerializer(Response response)
    {
        string path = "D:/Serialization.xml";

        var xs = new XmlSerializer(typeof(Response));           

        using (var fs = new FileStream(path, FileMode.OpenOrCreate))
        {
            using (var sw = new StreamWriter(fs))
            {
                using (var xw = new XmlTextWriter(sw))
                {
                    xw.Formatting = System.Xml.Formatting.Indented;
                    xs.Serialize(xw, response);
                    xw.Flush();
                }
            }

            fs.Close();
        }
    }
}