]]>remove empty elements from a xml string using RegExpresshttp://m.tkk7.com/vcok/archive/2008/12/04/244465.html涓庝綘鍚岄涓庝綘鍚岄Thu, 04 Dec 2008 14:53:00 GMThttp://m.tkk7.com/vcok/archive/2008/12/04/244465.htmlhttp://m.tkk7.com/vcok/comments/244465.htmlhttp://m.tkk7.com/vcok/archive/2008/12/04/244465.html#Feedback0http://m.tkk7.com/vcok/comments/commentRss/244465.htmlhttp://m.tkk7.com/vcok/services/trackbacks/244465.html
* Remove all elements with empty value except in exceptionElement
* @param xml
* @return
*/
private String removeAllEmptyElements(String xml) {
String[] exceptionElement={"AddressHistoryInformation"};
String result=xml;
String regExp="<(\\w+)></\\1>|<(\\w+)/>";
Pattern pattern=Pattern.compile(regExp);
Matcher matcher=pattern.matcher(result);
String elementName;
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
elementName=matcher.group(1)!=null?matcher.group(1):matcher.group(2);
if (!isExceptionElement(elementName, exceptionElement)) {
matcher.appendReplacement(sb, "");
}
}
matcher.appendTail(sb);
return sb.toString();
}
/**
* returns true if an elementName is in the exception array
* @param elementName
* @param exceptionArray
* @return
*/
private boolean isExceptionElement(String elementName, String[]exceptionArray) {
for (String exceptionStr:exceptionArray) {
if (elementName.equalsIgnoreCase(exceptionStr)) {
return true;
}
}
return false;
}