[英]How do I tell xmlwriter to ignore empty nodes in C#?
I am serializing the following entity into XML to send to our Google Search Appliance: 我将以下实体序列化为XML以发送到我们的Google Search Appliance:
[Serializable]
[XmlType("record")]
public class GSADocumentRecord
{
public enum RecordActions
{
Add,
Delete
}
[XmlAttribute(AttributeName = "url")]
public string URL { get; set; }
[XmlAttribute(AttributeName = "mimetype")]
public string MimeType { get; set; }
[XmlAttribute(AttributeName = "last-modified")]
public string LastModified { get; set; }
[XmlAttribute(AttributeName = "action")]
public string Action { get; set; }
[XmlArray(ElementName = "metadata", Order = 0)]
public List<GSADocumentRecordMeta> MetaData { get; set; }
[XmlElement(ElementName = "content", Order = 1, Type = typeof(CDATA))]
public CDATA Content { get; set; }
}
The problem is that when this is serialzied without any MetaData
entries, it adds <metadata />
to the xml. 问题是当这是序列化而没有任何MetaData
条目时,它会将<metadata />
添加到xml。 This is a problem because GSA (for whatever reason) errors out if there is an empty metadata node when used for some actions. 这是一个问题,因为如果在用于某些操作时存在空元数据节点,则GSA(无论出于何种原因)会出错。
I am serializing this class with the following code: 我使用以下代码序列化此类:
var ms = new System.IO.MemoryStream();
XmlSerializer xml = new XmlSerializer(this.GetType());
StreamWriter sw = new StreamWriter(ms);
XmlWriter xw = new XmlTextWriter(sw);
xw.WriteStartDocument();
xw.WriteDocType("gsafeed", "-//Google//DTD GSA Feeds//EN", null, null);
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
xml.Serialize(xw, this, ns);
ms.Position = 0;
How can I tell the XmlWriter
to ignore this element if the list is empty? 如果列表为空,如何告诉XmlWriter
忽略此元素?
Having a self-closing tag certainly seems legal, it sounds like the parser on their side is causing the problem. 拥有一个自动关闭标签肯定是合法的,听起来像他们一边的解析器导致问题。 You could write the XML out to a string first, and then do a .Replace("<metadata />", "")
. 您可以先将XML写入字符串,然后再执行.Replace("<metadata />", "")
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.