C# 如何在xml序列化期间包含空属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18515158/
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-10 12:27:35  来源:igfitidea点击:

How to include null properties during xml serialization

c#xmlserialization

提问by Davita

Currently, the code below omits null properties during serialization. I want null valued properties in the output xml as empty elements. I searched the web but didn't find anything useful. Any help would be appreciated.

目前,下面的代码在序列化过程中省略了 null 属性。我希望输出 xml 中的空值属性作为空元素。我在网上搜索,但没有找到任何有用的东西。任何帮助,将不胜感激。

        var serializer = new XmlSerializer(application.GetType());
        var ms = new MemoryStream();
        var writer = new StreamWriter(ms);
        serializer.Serialize(writer, application);
        return ms;

Sorry, I forgot to mention that I want to avoid attribute decoration.

对不起,我忘了说我想避免属性修饰。

采纳答案by Emanuele Greco

Can you control the items that have to be serialized?
Using

你能控制必须序列化的项目吗?
使用

[XmlElement(IsNullable = true)]
public string Prop { get; set; }

you can represent it as <Prop xsi:nil="true" />

你可以将它表示为 <Prop xsi:nil="true" />

回答by Anand

You can use also use the following code. The pattern is ShouldSerialize{PropertyName}

您也可以使用以下代码。图案是ShouldSerialize{PropertyName}

public class PersonWithNullProperties
{
    public string Name { get; set; }
    public int? Age { get; set; }
    public bool ShouldSerializeAge()
    {
        return true;
    }
}

  PersonWithNullProperties nullPerson = new PersonWithNullProperties() { Name = "ABCD" };
  XmlSerializer xs = new XmlSerializer(typeof(nullPerson));
  StringWriter sw = new StringWriter();
  xs.Serialize(sw, nullPerson);

XML

XML

<?xml version="1.0" encoding="utf-16"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://
www.w3.org/2001/XMLSchema">
  <Name>ABCD</Name>
  <Age xsi:nil="true" />
</Person>