c# - 将字段标记为具有属性 [XmlElement] 的 IsRequired

标签 c# xml serialization xsd xml-serialization

我有一个想要序列化的类

[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://xyz.com/schema")]
public class Customer
{
    [System.Xml.Serialization.XmlElementAttribute(Order = 0)]
    public int Id { get; set; }

    [System.Xml.Serialization.XmlElementAttribute(Order = 1)]
    public string Name { get; set; }

    [System.Xml.Serialization.XmlElementAttribute(Order = 2)]
    public string Url{ get; set; }

    [System.Xml.Serialization.XmlElementAttribute(Order = 3)]
    public string Count { get; set; }
}

反序列化时,如果 Url 为 null,则输出 XML 不包含 Url 节点。 如何将其标记为必填字段以便每次都会创建 Url 节点?

最佳答案

IsNullable 属性应该可以做到这一点。

 [System.Xml.Serialization.XmlElementAttribute(Order = 2,IsNullable=true)]

如果它设置为 true,它应该生成标签(根据 MSDN)。

If the IsNullable property is set to true, the xsi:nil attribute is generated for class members that have been set to a null reference (Nothing in Visual Basic). For example if you set a field named MyStringArray to a null reference (Nothing in Visual Basic), the XmlSerializer generates the following XML code.

<MyStringArray xsi:nil = "true" />

关于c# - 将字段标记为具有属性 [XmlElement] 的 IsRequired,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9359874/

相关文章:

c# - 包含相同元素的两个数组可以不相等吗?

C# WPF : Geometric Operations

sql-server - 使用 SSIS 导入列时 XML 变成中文/日文

C# 序列化问题

c# - 如何向现有类添加 [OnDeserialized] 功能?

C++ 相当于 Python getattr

C#如何杀死一个阻塞的线程?

java - 使用模数和指数在 C# 中进行 RSA/ECB/PKCS1Padding 解密

xml - Eclipse:非 XML 文件的 XML 语法着色

c# - 从 WCF 服务返回类型化数据集导致未找到 'xs:string'