避免使用XML自行关闭标记

时间:2014-01-20 23:02:55

标签: c# xml

我正在尝试下面的代码来序列化一个对象。问题是如果某些元素为null,那么它们具有如下所示的自闭项标记:

<City/>我希望这样<City> </City>。有什么想法吗?

private string GetXMLFromObject(object o)
{
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.OmitXmlDeclaration = true;
    MemoryStream ms = new MemoryStream();
    XmlWriter writer = XmlWriter.Create(ms, settings);
    XmlSerializerNamespaces names = new XmlSerializerNamespaces();
    names.Add("", "");
    XmlSerializer serializer = new XmlSerializer(o.GetType());
    serializer.Serialize(writer, o, names);
    ms.Flush();
    ms.Seek(0, SeekOrigin.Begin);
    StreamReader sr = new StreamReader(ms);
    string xml = sr.ReadToEnd();
    return xml;
}

1 个答案:

答案 0 :(得分:2)

关于有效性,<City/><City> </City>都有效,任何XML解析器都会正确处理。

如果您仍想强迫它,请执行以下操作。您正在寻找的是WriteFullEndElement()方法。 See MSDN了解更多信息:

writer.WriteStartElement("City");
writer.WriteString(inputCity);
writer.WriteFullEndElement();

City为空时,这会强制它将<City></City>序列化为inputCity