Click here to Skip to main content
15,609,498 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
public string XmlSerializer(Object item)
    StringBuilder builder = new StringBuilder();
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.OmitXmlDeclaration = true;
    settings.Indent = true; 

    using (XmlWriter xmlWriter = XmlWriter.Create(builder, settings))
        XmlSerializer xmlSerializer = new XmlSerializer(item.GetType());
        XmlSerializerNamespaces nameSpaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
        nameSpaces.Add("", "");
        xmlSerializer.Serialize(xmlWriter, item, nameSpaces);

    return builder.ToString(); 

O/P :-
<currency_name />   <!-- Need to Avoid This Self Closing Tag -->
Updated 16-Nov-15 23:44pm
Mehdi Gholam 17-Nov-15 5:55am    
Maciej Los 17-Nov-15 9:30am    
Good question!

1 solution

One option is to perform some post-processing of the output using regular expressions:

First define the following Regex to find the empty tags:
static Regex emptyElementRegex = new Regex(@"<(\w+)\s*/>");

Then process your output to replace all matching occurrences:
var result = builder.ToString();
result = emptyElementRegex.Replace(result, @"<$1>");

This should transform ALL self-closing tags without attributes.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900