简体   繁体   English

XmlIgnore仅在序列化中

[英]XmlIgnore ONLY in Serialization

        private string _password;

        public string Password
        {
            get 
            {
                return _password; 
            }
            set
            {
                if (_password != value)
                {
                    _password = PasswordEncryptor.Encode(value);
                    OnPropChanged("Password");                
                }
            }
        }

PasswordEncryptor is a class where I call the Encode method to encode. PasswordEncryptor是我调用Encode方法进行编码的类。 And after the Password is encoded, it is serialized by XmlSerializer to a file in disk. Password被编码后,由XmlSerializer序列化为磁盘中的文件。 However, every time when the program starts, the file is deserialized, and in set , PasswordEncryptor.Encode() encodes the Password again. 但是,每次程序启动时,该文件都会反序列化,并且在setPasswordEncryptor.Encode()再次对Password编码。 Is there a way I can [XmlIgnore] it ONLY in deserialization? 有没有办法只能在反序列化中[XmlIgnore]

XmlAttributeOverrides can help in this scenario. XmlAttributeOverrides在这种情况下可以提供帮助。

From MSDN MSDN

Allows you to override property, field, and class attributes when you use the XmlSerializer to serialize or deserialize an object 使用XmlSerializer序列化或反序列化对象时,允许您覆盖属性,字段和类属性

Using this we can make a particular property to be ignored during deserialization. 使用此方法,我们可以使反序列化过程中忽略的特定属性。

It will be something like this... 会是这样的...

XmlElementAttribute attr = new XmlElementAttribute();
attr.ElementName = "<elementName>";

XmlAttributes attrs = new XmlAttributes();
attrs.XmlIgnore = true;
attrs.XmlElements.Add(attr);

XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();
attrOverrides.Add(typeof(<className>), "<elementName>", attrs);

// use this when deserializing
XmlSerializer s = new XmlSerializer(typeof(<className>), attrOverrides);

// use this when serializing
XmlSerializer s = new XmlSerializer(typeof(<className>));

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

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