Xml Serialization - Render Empty Element

前端 未结 5 1461
说谎
说谎 2021-02-07 03:44

I am using the XmlSerializer and have the following property in a class

public string Data { get; set; }

which I need to be output exactly like

相关标签:
5条回答
  • 2021-02-07 04:26

    try to use public bool ShouldSerialize_PropertyName_(){} with setting the default value inside.

    public bool ShouldSerializeData()
    {
       Data = Data ?? "";
       return true;
    }
    

    Description of why this works can be found on MSDN.

    0 讨论(0)
  • 2021-02-07 04:39

    The solution to this was to create a PropertyNameSpecified property that the serializer uses to determine whether to serialize the property or not. For example:

    public string Data { get; set; }
    
    [XmlIgnore]
    public bool DataSpecified 
    { 
       get { return !String.IsNullOrEmpty(Data); }
       set { return; } //The serializer requires a setter
    }
    
    0 讨论(0)
  • 2021-02-07 04:39

    You could try adding the XMLElementAttribute like [XmlElement(IsNullable=true)] to that member. That will force the XML Serializer to add the element even if it is null.

    0 讨论(0)
  • 2021-02-07 04:40

    I was recently doing this and there is an alternative way to do it, that seems a bit simpler. You just need to initialise the value of the property to an empty string then it will create an empty tag as you required;

    Data = string.Empty;
    
    0 讨论(0)
  • 2021-02-07 04:44

    You could try adding the XMLElementAttribute like [XmlElement(IsNullable=true)] to that member and also set in the get/set property something like this:

    [XmlElement(IsNullable = true)] 
    public string Data 
    { 
        get { return string.IsNullOrEmpty(this.data) ? string.Empty : this.data; } 
        set 
        { 
            if (this.data != value) 
            { 
                this.data = value; 
            } 
        } 
    } 
    private string data;
    

    And so you will not have:

    <Data xsi:nil="true" />
    

    You will have this on render:

    <Data />
    
    0 讨论(0)
提交回复
热议问题