首页 > 解决方案 > 忽略空元素的 C# 对象序列化到 XML

问题描述

[XmlRoot("SAPInformationInterchangeXML")]
public class EWayBillResponseXML
{
    [XmlElement(ElementName = "SAPBusinessNetworkCustomerID")]
    public string SAPBusinessNetworkCustomerID { get; set; }

    [XmlElement(ElementName = "INVOIC")]
    public ResponseINVOIC Invoice { get; set; }
}

public class ResponseINVOIC
{
    [XmlElement(ElementName = "HeaderInformation")]
    public string HeaderInformation { get; set; }

    [XmlElement(ElementName = "AuthorizationInformation")]
    public string AuthorizationInformation { get; set; }
}


    var encoding = Encoding.GetEncoding("ISO-8859-1");
    XmlWriterSettings xmlWriterSettings = new XmlWriterSettings
    {
        Indent = true,
        OmitXmlDeclaration = false,
        Encoding = encoding
    };

    string requestHeaderInformation = null, requestAuthorizationInformation = null;

    EWayBillResponseXML obj = new EWayBillResponseXML
                    {
                        SAPBusinessNetworkCustomerID = "1",
                        Invoice = new ResponseINVOIC
                        {
                            HeaderInformation = requestHeaderInformation,
                            AuthorizationInformation = requestAuthorizationInformation
                        }
    };

    System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(obj.GetType());

    using (var stream = new MemoryStream())
    {
        using (var xmlWriter = XmlWriter.Create(stream, xmlWriterSettings))
        {
            x.Serialize(xmlWriter, obj);
        }
        Console.WriteLine(encoding.GetString(stream.ToArray()));
    }

我创建了 2 个名为 EWayBillResponseXML 和 ResponseINVOIC 的对象。我尝试使用上面的代码片段进行序列化。它给了我序列化的 XML,但它也返回空对象元素。我不需要序列化 ​​XML 中的空对象。你能帮帮我吗。

目前得到输出:

<?xml version="1.0" encoding="iso-8859-1"?>
<SAPInformationInterchangeXML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SAPBusinessNetworkCustomerID>1</SAPBusinessNetworkCustomerID>
<INVOIC />
</SAPInformationInterchangeXML>

预期输出:

<?xml version="1.0" encoding="iso-8859-1"?>
<SAPInformationInterchangeXML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SAPBusinessNetworkCustomerID>1</SAPBusinessNetworkCustomerID>
</SAPInformationInterchangeXML>

标签: c#xmlxml-serializationxmlserializer

解决方案


您可以将以下方法添加到您的可序列化类 ( EWayBillResponseXML) 中:

        public bool ShouldSerializeInvoice()
        {
            return Invoice != null;
        }

您可以在此处阅读更多相关信息


推荐阅读