How to replace nth occurrence in the xml template in Java?

Viewed 76

Here I am doing automation with Java, serenity with rest-assured. So I want to replace the 2nd <p> & </p> tags with a blank string.

Here I attached the template

<Request>    
    <P>
        <n>name1</n>
        <v>${value1}</v>
    </P>
    <P>
        <n>name2</n>
        <v>${value2}</v>
    </P> 
   <P>
        <n>name3</n>
        <v>value3</v>
    </P> 
</Request>

I am using the below code to replace the 2nd <p> and </p> tags. But it was replaced the all <p> &</p> tags(first and last <p> & </p> tags also)

String request = exampleTemplate.replace("${value1}", "XYZ")
                .replace("<P>", "")
                .replace("<v>${value2}</v>", "1234")
                .replace("</P>", "")
                .replace("${value3}", "AAA");

How can I replace only the 2nd <p> and </p> tags?

1 Answers

You can match both the first and second <p> elements together.

String res = str.replace("${value1}", "XYZ")
                .replace("<v>${value2}</v>", "1234")
                .replace("${value3}", "AAA")
                .replaceFirst("(?s)(<P>.*?</P>\\s*)<P>(.*?)</P>", "$1$2");

Demo

Related