1

我有以下实用程序方法来帮助将对象序列化为 XML:

public static string Serialize(object input) {
    if (input != null) {
        using (var sw = new StringWriter()) {
            var serializer = new System.Xml.Serialization.XmlSerializer(_type);
            serializer.Serialize(sw, input);
            return sw.ToString();
        }
    } else
        return null;
}

这适用于基本类型。但是如果我的类型有一个接口属性,那么它就行不通了。我的类型是否可以实现一个接口,该接口仅指定我希望在序列化时包含的类型的属性?

我会很感激你的帮助,因为我不太了解如何去做,但它似乎是可能的。谢谢

4

2 回答 2

1

Have a look at Controlling XML Serialization Using Attributes

Attributes can be used to control the XML serialization of an object or to create an alternate XML stream from the same set of classes.

Preventing Serialization with the XmlIgnoreAttribute
There might be situations when a public property or field does not need to be serialized. For example, a field or property could be used to contain metadata. In such cases, apply the XmlIgnoreAttribute to the field or property and the XmlSerializer will skip over it.

XmlIgnoreAttribute Class

Instructs the Serialize method of the XmlSerializer not to serialize the public field or public read/write property value.

Something like in the example

public class Group
{
   // The XmlSerializer ignores this field.
   [XmlIgnore]
   public string Comment;

   // The XmlSerializer serializes this field.
   public string GroupName;
}
于 2013-06-13T16:15:13.733 回答
1

如果您在类成员前面加上 XmlIgnore 属性,则 XmlSerializer 不会对它进行序列化/反序列化。例如:

// Super secret text here, must not be serialised
[XmlIgnore()]
public String SecurityCode = null;
于 2013-06-13T16:15:59.673 回答