Xml Serialization - Render Empty Element

泪湿孤枕 提交于 2019-12-18 14:56:09

问题


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 so

<Data />

How would I go about achieving this?


回答1:


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;



回答2:


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
}



回答3:


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.




回答4:


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.




回答5:


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 />


来源:https://stackoverflow.com/questions/2330001/xml-serialization-render-empty-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!