G. T. G. T. - 4 months ago 15
C# Question

Converting the Xml tags

In my xml some of the xml element are empty for example:

<A></A>


So I want to modify the elements that are of the type shown above to convert to
<A/>
type element so how can we do it in C# and update in the file.

Answer

Here's what I came up with:

private static void FormatEmptyNodes(XmlNode rootNode)
{
    foreach (XmlNode childNode in rootNode.ChildNodes)
    {
        FormatEmptyNodes(childNode);

        if(childNode is XmlElement)
        {
            XmlElement element = (XmlElement) childNode;
            if (string.IsNullOrEmpty(element.InnerText)) element.IsEmpty = true;
        }
    }
}

Then use it like this:

var doc = new XmlDocument();
doc.Load(inputFilePath);
FormatEmptyNodes(doc);
doc.Save(outputFilePath);