Android XML String to Text Convert getValueWithSurroundingTags(String xml, String tag)

Here you can find the source of getValueWithSurroundingTags(String xml, String tag)

Description

get Value With Surrounding Tags

Parameter

Parameter Description
xml a parameter
tag - without brackets, tag="body" will return "<body ...>.....</body>"

Declaration

public static String getValueWithSurroundingTags(String xml, String tag) 

Method Source Code

//package com.java2s;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    /**/*w  w w. j a  v a2 s .com*/
     * 
     * @param xml
     * @param tag - without brackets, tag="body" will return "<body ...>.....</body>"
     * @return
     */
    public static String getValueWithSurroundingTags(String xml, String tag) {
        String regexCode = "(<" + tag + ".*?>)(.*?)(</" + tag + ">)";
        return regexExtract(xml, regexCode);
    }

    /**
     * Extracts regex match from string
     * @param string to search
     * @param pattern regex pattern
     * @return matched string, or null if nothing found (or null if any of the parameters is null)
     */
    public static String regexExtract(String string, String pattern) {
        if (string == null || pattern == null) {
            return null;
        }

        Matcher m = regexGetMatcherForPattern(string, pattern);
        if (m == null) {
            return null;
        }

        if (m.find()) {
            return m.group(0);
        } else
            return null;
    }

    public static Matcher regexGetMatcherForPattern(String string,
            String pattern) {
        if (string == null || pattern == null) {
            return null;
        }

        /**
         * strip newline characters because it doesn't work well with this.
         */
        //    string = string.replace("\n", "");

        Pattern p = Pattern.compile(pattern, Pattern.DOTALL
                | Pattern.MULTILINE);
        Matcher m = p.matcher(string);

        return m;
    }
}

Related

  1. getMatcherForXmlTags(String xml, String tag)
  2. getMatcherWithSurroundingTags(String xml, String tag)
  3. getValueInsideXmlTags(String xml, String openTag, String closeTag)
  4. getValueInsideXmlTags(String xml, String tag)