(递归?)正则表达式删除空的xml标签 [英] (Recursive?) Regex to remove empty xml tags

查看:50
本文介绍了(递归?)正则表达式删除空的xml标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 xml 文件中删除所有空标签.但是,我的选择非常有限,因此我想使用正则表达式(此处提供并在内部已知).

I'd like to remove all empty tags from an xml file. However, my options are very limited, so I'd like to use a regex (which is available and known internally here).

我对正则表达式删除它们变体中的空标签没有问题,但嵌套的空标签有点困难,因为我的正则表达式只会深入.

I have no problem with the regex to remove the empty tags in their variations, but the nested empty tags are a bit harder, as my regex will only go one deep.

我相信这是因为我的递归中的命名捕获组,但我无法修复它.

I believe it's because of the named capture group in my recursion, but I'm not able to fix it.

这是我目前所拥有的:这里

最好的问候和感谢,

劳伦特

推荐答案

试试这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml = 
                "<root>" +
                    "<tag1>Good</tag1>" +
                    "<tag2 element=\"Good\"></tag2>" +
                    "<tag3 element=\"Good\" />" +
                    "<tag4></tag4>" +
                    "<tag13>" +
                    "</tag13>" +
                    "<tag5 />" +
                    "<tag6/>" +
                    "<tag7>" +
                        "<tag7.1>good</tag7.1>" +
                    "</tag7>" +
                    "<tag8>" +
                        "<tag8.1></tag8.1>" +
                    "</tag8>" +
                    "<tag9>" +
                        "<tag9.1 />" +
                    "</tag9>" +
                    "<tag10>" +
                        "<tag10.1/>" +
                    "</tag10>" +
                    "<tag10>" +
                        "<tag10.1>Wel iets</tag10.1>" +
                    "</tag10>" +
                    "<tag11>" +
                        "<tag11.1 element=\"Good\"/>" +
                    "</tag11>" +
                    "<tag12>" +
                        "<tag12.1></tag12.1>" +
                        "<tag12.2>" +
                            "<tag12.2.1></tag12.2.1>" +
                        "</tag12.2>" +
                    "</tag12>" +
                    "</root>";
            XElement root = XElement.Parse(xml);
            var deleteElements = root.Descendants().Where(x => (x.Descendants().Count() == 0) && (x.Attributes().Count() == 0) && (x.Value.Length == 0)).ToList();
            foreach (XElement deleteElement in deleteElements)
            {
                deleteElement.Remove();
            }
        }
    }
}
​

这篇关于(递归?)正则表达式删除空的xml标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆