2

I want to split some XML text into parts:

xmlcontent = "<tagA>text1<tagB>text2</tagB></tagA>";

In C# i use

string[] splitedTexts = Regex.Split(xmlcontent, "(<.*?>)|(.+?(?=<|$))");

The result is

splitedTexts = ["<tagA>", "text1", "<tagB>", "text2", "</tagB>", "</tagA>"]

How can do it in Java?

I have tried

String[] splitedTexts = xmlcontent.split("(<.*?>)");

but the result is not like my expecting.

4
  • What is the result you got from the Java split ? Commented Mar 6, 2014 at 10:11
  • 1
    The parameter to split defines the delimiter to split at. You seem to want to find matches. Commented Mar 6, 2014 at 10:14
  • have you any function in java line the function in C# that i mention Commented Mar 6, 2014 at 10:20
  • @Minh Le: You can use the regex package to find matches or refine the pattern to find delimiters as in my answer. Commented Mar 6, 2014 at 10:21

2 Answers 2

5

The parameter to split defines the delimiter to split at. You want to split before < and after > hence you can do:

String[] splitedTexts = xmlcontent.split("(?=<)|(?<=>)");
Sign up to request clarification or add additional context in comments.

Comments

3

If you want to use Regex:

public static void main(String[] args) {
    String xmlContent = "<xml><tagA>text1</tagA><tagB>text2</tagB></xml>";
    Pattern pattern = Pattern.compile("(<.*?>)|(.+?(?=<|$))");
    Matcher matcher = pattern.matcher(xmlContent);
    while (matcher.find()) {
        System.out.println(matcher.group());
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.