簡體   English   中英

Xml序列化動態忽略

[英]Xml Serialization Dynamic Ignore

我正在嘗試以特定格式生成xml文檔。 我想跳過根據屬性的值序列化屬性。

public class Parent
{
    public Parent()
    {
        myChild = new Child();
        myChild2 = new Child() { Value = "Value" };
    }
    public Child myChild { get; set; }
    public Child myChild2 { get; set; }
}

public class Child
{
    private bool _set;
    public bool Set { get { return _set; } }

    private string _value = "default";
    [System.Xml.Serialization.XmlText()]
    public string Value
    {
        get { return _value; }
        set { _value = value; _set = true; }
    }
}

System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(Parent));
x.Serialize(Console.Out, new Parent());

如果Set為false,我希望整個屬性不被序列化,我得到的xml應該是

<Parent>
   <myChild2>default</myChild2>
</Parent>

代替

<Parent>
   <myChild/>
   <myChild2>default</myChild2>
</Parent>

有什么方法可以用IXmlSerializable或其他任何東西干凈利落地做到這一點?

謝謝!

有一個ShouldSerialize *模式(由TypeDescriptor引入,但由其他一些代碼區域識別,例如XmlSerializer):

public bool ShouldSerializemyChild() {
     return myChild != null && myChild.Set;
}

那應該排序。

但是,更簡單的選擇是將其賦值為null。

如果“mychild”是由數組定義的,我認為它可以做得很好......

public class Parent
{
    public Parent()
    {
        myChild = new Child[]{ new Child(){Value = "Value"}};
        //myChild2 = new Child() { Value = "Value" };
    }
    public Child[] myChild { get; set; }
    //public Child myChild2 { get; set; }
}

我認為這可能會奏效,但你必須要超越Equals方法

[DefaultValue(new Child())]
public Child myChild{ get; set; }

剛剛寫了這段代碼以獲得樂趣,也許在這個過程中學到了一些東 如果該屬性包含一個名為Set的方法返回bool,並且其當前值為false,則應將any屬性設置為null。 通過將值設置為false,它應該解決序列化器問題。 有什么建議:

public static void RemoveUnsetObjects(object currentObject)
{
    var type = currentObject.GetType();
    if (currentObject is IEnumerable)
    {
        IEnumerable list = (currentObject as IEnumerable);
        foreach (object o in list)
        {
            RemoveUnsetObjects(o);
        }
    }
    else
    {
        foreach (var p in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
        {
            var propertyValue = p.GetValue(currentObject, null);
            if (propertyValue == null)
                continue;
                    var setPropInfo = p.PropertyType.GetProperty("Set", typeof(bool));
            if (setPropInfo != null)
            {
                var isSet = (bool)setPropInfo.GetValue(propertyValue, null);
                if (!isSet)
                {
                    p.SetValue(currentObject, null, null);
                }
            }
            else
            {
                RemoveUnsetObjects(propertyValue);
            }
        }
    }
}

暫無
暫無

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

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