1

I have the following xml fragment as a string:

String str ="<xs:user>userName</xs:user><xs:password>userPassword</xs:password>
<xs:address>addressString</xs:address>";

What would be the best way to replace userPassword with xxxxxxx?

Edit: xs (namespace) can vary.

edgmsh
  • 5
  • 3

4 Answers4

1

Try using this:

String str2 = str.replaceFirst("<xs:password>.*?</xs:password>", "<xs:password>xxxxxxxxxx</xs:password>");`
anirudh
  • 4,116
  • 2
  • 20
  • 35
1

This should do it. This is the most simple solution I can think of right now.

public static void main(String[] args) {
    String str = "aaaaa<xs:password>userPassword</xs:password>bbbbbbbbbb";
    String newPassword = "test";
    String s2 = str.replaceAll("<xs:password>[^<]*</xs:password>", "<xs:password>" + newPassword + "</xs:password>");
    System.out.println(s2);
}
peter.petrov
  • 38,363
  • 16
  • 94
  • 159
0

An oldschool crawl-through-the-string approch would be:

    String in =
            "<xs:user>userName</xs:user>" +
            "<xs:password>userPassword</xs:password>" +
            "<xs:address>addressString</xs:address>";

    int pwStart = in.indexOf("<xs:password>") + 13;
    int pwLen   = in.indexOf("</xs:password>") - pwStart;

    StringBuilder out = new StringBuilder();

    out.append(in.substring(0, in.indexOf("<xs:password>") + 13));
    for (int i = 0; i < pwLen; i++) {
        out.append("x");
    }
    out.append(in.substring(in.indexOf("</xs:password>")));

    System.out.printf("%s\n", in);
    System.out.printf("%s\n", out);
ifloop
  • 8,079
  • 2
  • 26
  • 35
0

In Java:

public static void replace(){

    String str =
            "<xs:user>userName</xs:user>" +
            "<xs:password>userPassword</xs:password>" +
            "<xs:address>addressString</xs:address>";

    String[] s = str.split("><");

    String[] t = s[1].split("password>");

    String[] a = t[1].split("</xs:");

    System.out.println(a[0]);

    String newS = s[0] + "><" + t[0] + "password>" + "YOUR XXXXXXX GOES HERE" + "</xs:" + a[1] + "><" + s[2];

    System.out.println(newS);

}

Hope this helps.

luiscosta
  • 855
  • 1
  • 10
  • 16