Java Remove empty XML tags

前端 未结 9 2385
死守一世寂寞
死守一世寂寞 2020-12-11 16:57

I\'m looking for a simple Java snippet to remove empty tags from a (any) XML structure


    bla
    <         


        
9条回答
  •  醉酒成梦
    2020-12-11 17:56

    public static void main(String[] args) {
    
        final String regex1 = "<([a-zA-Z0-9-\\_]*)[^>]*/>";
        final String regex2 = "<([a-zA-Z0-9-\\_]*)[^>]*>\\s*";
    
        String xmlString = "bla";
        System.out.println(xmlString);
    
        final Pattern pattern1 = Pattern.compile(regex1);
        final Pattern pattern2 = Pattern.compile(regex2);
    
        Matcher matcher1;
        Matcher matcher2;
        do { 
            xmlString = xmlString.replaceAll(regex1, "").replaceAll(regex2, "");
            matcher1 = pattern1.matcher(xmlString);
            matcher2 = pattern2.matcher(xmlString);
        } while (matcher1.find() || matcher2.find());
    
        System.out.println(xmlString);
    }
    

    Console:

    
        bla
        
        
        
            
                
                    
                
            
            
        
    
    
    
        bla
    
    

    Online demo here

提交回复
热议问题