0

I am trying to serialize an object to XML and the problem that I am getting is that the object gets serialized to

<something />  

instead of

<something/>

I believe that both are valid XML syntax, but I have to get <something/>

Here is my code

public static string Serialize<T>(T ObjectToSerialize)
{
    XmlWriterSettings settings = new XmlWriterSettings()
    {
        OmitXmlDeclaration = true,
        Encoding = Encoding.UTF8,
    };

    XmlSerializer xmlSerializer = new XmlSerializer(ObjectToSerialize.GetType());

    using (StringWriter textWriter = new StringWriter())
    {
        using (var xw = XmlWriter.Create(textWriter, settings))
        {
            xmlSerializer.Serialize(xw, ObjectToSerialize);

        }

        return textWriter.ToString();
    }
}

How can I fix it?

MZanetti
  • 86
  • 1
  • 8
mko
  • 6,638
  • 12
  • 67
  • 118
  • Did setting Indent=false helped you ? [Look at this answer for code](https://stackoverflow.com/questions/5414617/prevent-xmlserializer-from-formatting-output) – Manoj Choudhari Jan 07 '20 at 12:15
  • 3
    Also why do you want to omit the space ? If you are deserializing, it will not cause any issue as such. – Manoj Choudhari Jan 07 '20 at 12:16
  • It only occurs if the node is empty. Normally you get abc – jdweng Jan 07 '20 at 12:22
  • @ManojChoudhari Indent=false didnt help – mko Jan 07 '20 at 12:26
  • @ManojChoudhari I have to omit it, as it is requested by 3rd party integration. I agree with you that shouldnt be an issue, but I have to fix it... not sure how. – mko Jan 07 '20 at 12:26
  • @jdweng i agree, but the question is how to display an empty node like without hiding it completely – mko Jan 07 '20 at 12:27
  • 4
    This is [hard-coded](https://referencesource.microsoft.com/#System.Xml/System/Xml/Core/XmlTextWriter.cs,1159) – canton7 Jan 07 '20 at 12:31
  • Take a look [here](https://stackoverflow.com/questions/462741/space-before-closing-slash). Maybe it'll be more clear to you. – MZanetti Jan 08 '20 at 10:26

1 Answers1

0

May not be the most efficient solution, but you could do a simple String.Replace before returning serialized data in Serialize<T>().

Replacing

 return textWriter.ToString();

With

 return textWriter.ToString().Replace(" />","/>"); 
Anu Viswan
  • 17,797
  • 2
  • 22
  • 51