C# Xml 序列化 - 呈现空元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2330001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:29:05  来源:igfitidea点击:

Xml Serialization - Render Empty Element

c#xml-serialization

提问by Jaimal Chohan

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

我正在使用 XmlSerializer 并在类中具有以下属性

public string Data { get; set; }

which I need to be output exactly like so

我需要完全像这样输出

<Data />

How would I go about achieving this?

我将如何实现这一目标?

采纳答案by Jaimal Chohan

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

对此的解决方案是创建一个PropertyNameSpecified属性,序列化程序使用该属性来确定是否序列化该属性。例如:

public string Data { get; set; }

[XmlIgnore]
public bool DataSpecified 
{ 
   get { return !String.IsNullOrEmpty(Data); }
   set { return; } //The serializer requires a setter
}

回答by HalloDu

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.

您可以尝试向该[XmlElement(IsNullable=true)]成员添加 XMLElementAttribute 之类的内容。这将强制 XML Serializer 添加元素,即使它为空。

回答by Firedragon

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;

回答by Waleed A.K.

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

尝试使用public bool ShouldSerialize_PropertyName_(){}并在里面设置默认值。

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

Description of why this works can be found on MSDN.

可以在MSDN上找到为什么它起作用的描述。

回答by johnander11

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)] 之类的 XMLElementAttribute 添加到该成员,并在 get/set 属性中设置如下所示:

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