我将以下实体序列化为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; }
}
问题在于,如果没有任何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
忽略此元素?
答案 0 :(得分:2)
拥有自动关闭标签肯定是合法的,听起来像他们这边的解析器导致了问题。您可以先将XML写入字符串,然后执行.Replace("<metadata />", "")
。