none
Avoid Self Closing Tags in XML RRS feed

  • Question

  • Hi

    I am trying below code to serialize an object. The problem is if some elements are null then they have self closing tags like below:

    <City/> which i want to be like this <City> </City>. Any thoughts?

       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;
            }

    Monday, January 20, 2014 10:25 PM

Answers

  • Hi,

    Maybe you can do this by creating your own XmlTextWriter to pass into the serialization process.

    public class MyXmlTextWriter : XmlTextWriter
    {
        public MyXmlTextWriter(Stream stream) : base(stream, Encoding.UTF8)
        {
    
        }
    
        public override void WriteEndElement()
        {
            base.WriteFullEndElement();
        }
    }

    Fro more information, please try to refer to this similar thread:
    http://stackoverflow.com/questions/13539555/prevent-self-closing-tags-in-xmlserializer-when-no-data-is-present .

    Best Regards,
    Amy Peng


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Tuesday, January 21, 2014 2:16 AM
    Moderator