Remove empty XML tags

后端 未结 6 1399
执笔经年
执笔经年 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:15

    XmlTextReader is preferable if we are talking about performance (it provides fast, forward-only access to XML). You can determine if tag is empty using XmlReader.IsEmptyElement property.

    XDocument approach which produces desired output:

    public static bool IsEmpty(XElement n)
    {
        return n.IsEmpty 
            || (string.IsNullOrEmpty(n.Value) 
                && (!n.HasElements || n.Elements().All(IsEmpty)));
    }
    
    var doc = XDocument.Parse(original);
    var emptyNodes = doc.Descendants().Where(IsEmpty);
    foreach (var emptyNode in emptyNodes.ToArray())
    {
        emptyNode.Remove();
    }
    

提交回复
热议问题