c# - 忽略空元素的 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>
解决方案
您可以将以下方法添加到您的可序列化类 ( EWayBillResponseXML
) 中:
public bool ShouldSerializeInvoice()
{
return Invoice != null;
}
您可以在此处阅读更多相关信息。
推荐阅读
- r - 为多个时间序列图从数据帧中分离数据帧
- php - stripos vs glob 用于取消链接
- python - 如何锁定pdf选择文本不可用
- javascript - PowerShell 和 IE 自动化
- python - 如何在 Python 中正确排序重音字母?
- xpath - XQuery - 使用模式选择和显示子节点
- reactjs - jhipster 在 Internet Explorer11 上反应应用程序错误
- c++ - 具有两个(不同)变量比较运算符的增强 if 语句
- reactjs - React js - 问题实现路由器
- linux - Azure DevOps:“托管 Linux 预览版”和“托管 Ubuntu 1604”代理池有什么区别?