如何告诉xmlwriter忽略C#中的空节点?

时间:2021-04-17 19:27:16

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. This is a problem because GSA (for whatever reason) errors out if there is an empty metadata node when used for some actions.

问题是,当这是序列化而没有任何MetaData条目时,它会将 添加到xml。这是一个问题,因为如果在用于某些操作时存在空元数据节点,则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忽略此元素?

1 个解决方案

#1


1  

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(“ ”,“”)。

#1


1  

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(“ ”,“”)。