我有一个想要序列化的类
[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, thexsi: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 namedMyStringArray
to anull
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/