如何告诉xmlwriter忽略C#中的空节点
本文关键字:节点 何告诉 xmlwriter 忽略 | 更新日期: 2023-09-27 18:29:19
我正在将以下实体序列化为XML,以发送到我们的谷歌搜索设备:
[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; }
}
问题是,当它在没有任何MetaData
条目的情况下串行化时,它会将<metadata />
添加到xml中。这是一个问题,因为GSA(无论出于何种原因)在用于某些操作时,如果存在空的元数据节点,就会出错。
我正在用以下代码序列化这个类:
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;
如果列表为空,我如何告诉XmlWriter
忽略此元素?
拥有一个自关闭标记似乎是合法的,听起来好像是他们这边的解析器造成了问题。您可以先将XML写入字符串,然后执行.Replace("<metadata />", "")
。