Java examples for XML:XML String
Replaces a tag given by a tag name in an xml string.
//package com.java2s; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] argv) throws Exception { String tagname = "java2s.com"; String xmlstring = "java2s.com"; System.out.println(removeTag(tagname, xmlstring)); }//w w w. j av a 2 s. c o m /** * A static threadsafe map which contains compiled Regex Patterns. */ private static Map<String, Pattern> patterns = new ConcurrentHashMap<String, Pattern>(); /** * Replaces a tag given by a tagname in an xmlstring. * * @param tagname Name of the tag to be removed * @param xmlstring XmlString to be modified * @return modified XmlString */ public static String removeTag(String tagname, String xmlstring) { if (!patterns.containsKey(tagname)) { String regex = "(\\<" + tagname + ">.+?\\</" + tagname + ">)"; Pattern pattern = Pattern.compile(regex, Pattern.DOTALL | Pattern.MULTILINE); patterns.put(tagname, pattern); } Matcher matcher = patterns.get(tagname).matcher(xmlstring); if (matcher.find()) { xmlstring = matcher.replaceAll(""); } return xmlstring; } }