簡體   English   中英

將字符串屬性序列化為屬性,即使字符串為空

[英]Serialize string property as attribute, even if string is empty

public class Hat
{
    [XmlTextAttribute]
    public string Name { get; set; }
    [XmlAttribute("Color")]
    public string Color { get; set; }
}

var hat1 = new Hat {Name="Cool Hat", Color="Red"};
var hat2 = new Hat {Name="Funky Hat", Color=null};

這就是我得到的(注意 Funky Hat 上缺少顏色屬性):

<Hats>
 <Hat Color="Red">Cool Hat</Hat>
 <Hat>Funky Hat</Hat>
</Hats>

這就是我要的:

<Hats>
 <Hat Color="Red">Cool Hat</Hat>
 <Hat Color="">Funky Hat</Hat>
</Hats>

如何強制序列化程序創建一個空屬性而不是將其排除在外?

編輯:

原來我是個白痴,並創建了一個包含錯誤的示例,因為我想簡化示例的代碼。

如果 color 的值為 "" (或 string.empty),它實際上被序列化為一個空屬性。 但是,我確實有一個 null 值,而不是一個空字符串 - 因此它被遺漏了。

所以我想要的行為實際上已經是我創建的示例的行為。

對不起大家!

嘗試使用List<Hat>作為容器。 使用這個:

var hats = new List<Hat>
    {
        new Hat { Name = "Cool Hat", Color = "Red" }, 
        new Hat { Name = "Funky Hat", Color = string.Empty }
    };

using (var stream = new FileStream("test.txt", FileMode.Truncate))
{
    var serializer = new XmlSerializer(typeof(List<Hat>));
    serializer.Serialize(stream, hats);
}

我明白了:

<?xml version="1.0"?>
<ArrayOfHat xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Hat Color="Red">Cool Hat</Hat>
  <Hat Color="">Funky Hat</Hat>
</ArrayOfHat>

您可以嘗試將Specified屬性設置為 true。 另外,我相信您可以使用##Specified 屬性來控制序列化,如下所示:

[XmlAttribute("Color")]
public string Color { get; set; }
[XmlIgnore]
public bool ColorSpecified { get { return true; } }    // will always serialize

或者只要不是null就可以序列化:

[XmlIgnore]
public bool ColorSpecified { get { return this.Color != null; } }

有兩種方法可以做到這一點。

您可以使用[XmlElement(IsNullable=true)] ,這將強制識別 null 值。

您也可以使用 String.Empty 而不是“”。 這被識別為空字符串,而不是 null。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM