I am looking for a good approach that can remove empty tags from XML efficiently. What do you recommend? Regex? XDocument? XmlTextReader?
For example,
As always, it depends on your requirements.
Do you know how the empty tag will display? (e.g.
,
, etc.) I usually do not recommend using Regular Expressions (they are really useful but at the same time they are evil). Also considering a string.Replace
approach seems to be problematic unless your XML doesn't have a certain structure.
Finally, I would recommend using an XML parser approach (make sure your code is valid XML).
var doc = XDocument.Parse(original);
var emptyElements = from descendant in doc.Descendants()
where descendant.IsEmpty || string.IsNullOrWhiteSpace(descendant.Value)
select descendant;
emptyElements.Remove();