Click here to Skip to main content
15,886,091 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
C#
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 :-
HTML
<get_country_details_response>
<country_id>10.0000</country_id>
<country_name>10.0000</country_name> 
<currency_name />   <!-- Need to Avoid This Self Closing Tag -->
</get_country_details_response>
Posted
Updated 16-Nov-15 23:44pm
v3
Comments
Mehdi Gholam 17-Nov-15 5:55am    
Why?
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:
C#
static Regex emptyElementRegex = new Regex(@"<(\w+)\s*/>");

Then process your output to replace all matching occurrences:
C#
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