我将以下xml片段作为字符串:
String str ="<xs:user>userName</xs:user><xs:password>userPassword</xs:password>
<xs:address>addressString</xs:address>";
用xxxxxxx替换userPassword的最佳方法是什么?
编辑:xs(名称空间)可能会有所不同。
答案 0 :(得分:1)
尝试使用:
String str2 = str.replaceFirst("<xs:password>.*?</xs:password>", "<xs:password>xxxxxxxxxx</xs:password>");`
答案 1 :(得分:1)
这应该这样做。这是我现在能想到的最简单的解决方案。
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);
}
答案 2 :(得分:0)
旧学校的字符串爬行方法是:
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);
答案 3 :(得分:0)
在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);
}
希望这有帮助。