XmlSerializer:保留未知元素 [英] XmlSerializer: keep unknown elements

查看:54
本文介绍了XmlSerializer:保留未知元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从XML序列化/反序列化并从文件存储/恢复的类:

I have a class that is serialized into/deserialized from XML and stored in/restored from a file:

public class Customer
{
    public string FirstName;
    public string LastName;

    public Customer()
    {
    }

    public Customer(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }

    public static Customer Load(TextReader reader)
    {
        XmlSerializer deserializer = new XmlSerializer(typeof(Customer));
        return (Customer)deserializer.Deserialize(reader);
    }

    public void Save(TextWriter writer)
    {
        XmlSerializer serializer = new XmlSerializer(GetType());
        serializer.Serialize(writer, this);
    }
}

在该类的较新版本中,我添加了一个新属性

In a newer version of this class I added a new property

public string MiddleName;

一个常见的用例是,用户同时安装了我的程序的旧版本和新版本.他们都读取和写入相同的序列化文件.当新版本写入文件时,将写入所有三个属性( FirstName LastName MiddleName ).旧程序读取文件,但忽略未知元素 MiddleName .它保存的文件没有 MiddleName ,因此对于较新的程序,它的值将丢失.

It is a common use case that a user has installed both the old and new version of my program. They both read and write the same serialized file. When the new version writes the file, all three properties (FirstName, LastName, MiddleName) are written. The old program reads the file but omits the unknown element MiddleName. It saves the file without MiddleName, so it's value is lost for the newer program.

在反序列化时是否有存储原始XML的方法,并在序列化时将未知元素合并"回去?旧程序会忽略未知元素,但会将它们写回到文件中,这样新程序就不会丢失它们.

Is there a way to store the original XML when deserializing and 'merge' the unknown elements back in when serializing? The old program would ignore unknown elements but write them back into the file so they are not lost for the new program.

推荐答案

就像我在Mac OS X上一样,目前无法对其进行测试,但是

Can't test it right now as I'm on Mac OS X, but XmlAnyElement should work:

[XmlAnyElement]
public XmlElement[] Unsupported { get; set; }

这篇关于XmlSerializer:保留未知元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆