簡體   English   中英

使用PropertyInfo []作為映射將對象序列化為xml

[英]Serialize object to xml using PropertyInfo[] as mapping

我正在嘗試編寫一個通用方法來序列化從ITable接口繼承的對象。 我還希望有一個PropertyInfo []參數,在這里可以指定需要與該對象序列化的屬性。 那些不存在的將被忽略。 有沒有辦法告訴XmlSerialize僅序列化列出的那些屬性?

方法簽名:

public static string SerializeToXml<T>(T obj, PropertyInfo[] fields = null) where T : ITable

如果字段為null,則自動獲取所有字段。

if (fields == null)
{
    Type type = typeof(T);
    fields = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
}

通常,您可以使用屬性來執行此操作,具體地說,您可以將[XmlIgnore]屬性添加到您不想序列化的屬性中(請注意,這是您想要的方法的另一種方式)。

但是,由於您想在運行時執行此操作,因此您可以使用XmlAttributeOverrides猜測運行時是否覆蓋屬性。

因此,這樣的事情應該起作用:

public static string SerializeToXml<T>(T obj, PropertyInfo[] fields = null)
    where T : ITable
{
    Type type = typeof(T);

    IEnumerable<PropertyInfo> ignoredProperties;

    if (fields == null)
        ignoredProperties = Enumerable.Empty<PropertyInfo>();
    else
        ignoredProperties = type.GetProperties(
            BindingFlags.Public | BindingFlags.Instance)
            .Except(fields);

    var ignoredAttrs = new XmlAttributes { XmlIgnore = true };

    var attrOverrides = new XmlAttributeOverrides();

    foreach (var ignoredProperty in ignoredProperties)
        attrOverrides.Add(type, ignoredProperty.Name, ignoredAttrs);

    var serializer = new XmlSerializer(type, attrOverrides);

    using (var writer = new StringWriter())
    {
        serializer.Serialize(writer, obj);
        return writer.ToString();
    }
}

無關緊要的是,我認為命名包含屬性fields的參數非常令人困惑。

對於每個字段,聲明一個屬性,例如:

public bool ShouldSerializeX()
{
    return X != 0;
}

當您遍歷字段時,根據是否要序列化,將其屬性設置為true或false。

因此,例如,如果您在PropertyInfo沒有字段Address ,請將屬性ShouldSerializeAddress設置為false,而XmlSerializer應該忽略它。

檢查此答案以獲取更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM