Remove empty XML tags

后端 未结 6 1398
执笔经年
执笔经年 2020-12-09 18:39

I am looking for a good approach that can remove empty tags from XML efficiently. What do you recommend? Regex? XDocument? XmlTextReader?

For example,



        
6条回答
  •  温柔的废话
    2020-12-09 19:21

    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();
    

提交回复
热议问题