簡體   English   中英

C# 當值為 null 或空字符串時,XmlSerializer 不寫入標記

[英]C# XmlSerializer is not writing tags when the value is null or empty string

我可以找到很多詢問如何隱藏 XML 標簽的人和示例,但我找不到的是當值為 null 或空字符串時如何讓它寫入標簽。 對我來說,無論我嘗試了什么,包括添加將其標記為 IsNullable false/true(都嘗試過)的 XmlElement,MyProperty 的標簽永遠不會被寫入,除非它有值。

我試過了

[XmlElement(IsNullable = true)]

[XmlElement(IsNullable = false)]

兩者都沒有區別

這只是真實代碼的模型,保存是以這種方式完成的,因為它將它保存為現有 XmlDocument 的一部分,因此還有其他代碼加載並找到需要添加它的位置並再次保存整個文檔。 包括所有代碼然后刪除 IP 將需要大量工作和代碼頁。

public class MyClass
{
    public string MyProperty { get; set; }
}

var myClass = new MyClass();

var xmlSerializer = new XmlSerializer(MyClass.GetType());
var xmlSerializerNamespaces = new XmlSerializerNamespaces();
xmlSerializerNamespaces.Add("", "");
var xmlWriterSettings = new XmlWriterSettings
{
    Indent = true,
    OmitXmlDeclaration = true,
    Async = true
};

using var stringWriter = new StringWriter();
using (var xmlWriter = XmlWriter.Create(stringWriter, xmlWriterSettings))
{
    xmlSerializer.Serialize(xmlWriter, myClass, xmlSerializerNamespaces);
    await xmlWriter.FlushAsync();
    xmlWriter.Close();
    xmlWriter.Dispose();
}
await stringWriter.FlushAsync();
stringWriter.Close();
await stringWriter.DisposeAsync();

var xDocument = XDocument.Parse(stringWriter.ToString());
xDocument.Descendants().Where(e => string.IsNullOrEmpty(e.Value)).Remove();
xDocument.Save(myClass);

嘗試以下已使用 .NET 6 測試過的操作:

使用語句

  • using System.Xml;
  • using System.Xml.Serialization;

序列化到 XML 文件

private void SerializeToXMLFile(object obj, string xmlFilename)
{
    if (String.IsNullOrEmpty(xmlFilename))
        throw new Exception($"Error: XML filename not specified. (xmlFilename: '{xmlFilename}')");

    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = true;
    settings.OmitXmlDeclaration = true;

    using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(xmlFilename, settings))
    {
        //specify namespaces
        System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
        ns.Add(string.Empty, "urn:none");

        //create new instance
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());

        //write XML to file
        serializer.Serialize(writer, obj, ns);
    }
}    

選項1:

創建 class (名稱:MyClass)

[XmlRoot("myclass")]
public class MyClass
{
    [XmlElement(ElementName = "myproperty")]
    public string? MyProperty { get; set; } = string.Empty;
}

注意:將值設置為string.Empty ,以便在未設置值時保存它。

結果

在此處輸入圖像描述


選項 2:

創建 class (名稱:MyClass)

[XmlRoot("myclass")]
public class MyClass
{
    [XmlElement(ElementName = "myproperty", IsNullable = true)]
    public string? MyProperty { get; set; }
}

結果

在此處輸入圖像描述


用法

MyClass myClass = new MyClass();
SerializeToXMLFile(myClass, @"C:\Temp\Test.xml");

資源

暫無
暫無

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

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