英文:
How to add multiple arguments into XPath and replace %s to param
问题
我有一个字符串(例如):
xpath = //tagname[text()='param1']/tagname[text()='param2']/tagname[text()='param3']
变量param可以从1增加到n(param1,param2,param3 .... paramN)
我想要构建一个函数,将多个参数添加到xpath中,并且我必须在Java中使用String格式来将多个值放入xpath中,但不知道如何将param替换为%s并使用String格式来放入多个参数。
我该如何构建一个将param替换为%s的函数?
非常感谢。
英文:
I have a string (e.g):
xpath = //tagname[text()='param1']/tagname[text()='param2']/tagname[text()='param3']
var param can increase from 1 => n (param1, param2, param3 .... paramN)
I want to build a function to add multiple arguments into xpath and I have to use String format in Java to put multiple value into xpath and do not know how to replace param to %s and use String format put multiple arguments.
> How can i build a function with replace param to %s?
Thank you so much.
答案1
得分: 1
你可以在[tag:xpath]中用不同的变量替换,如下所示:
-
代码块:
String str1 = "stringA"; String str2 = "stringB"; String str3 = "stringC"; System.out.println("//tagname[text()='" + str1 + "']/tagname[text()='" + str2 + "']/tagname[text()='" + str3 + "']");
-
控制台输出:
//tagname[text()='stringA']/tagname[text()='stringB']/tagname[text()='stringC']
英文:
You can different variables to be replaced within the [tag:xpath] as follows:
-
Code Block:
String str1 = "stringA"; String str2 = "stringB"; String str3 = "stringC"; System.out.println("//tagname[text()='" +str1+ "']/tagname[text()='" +str2+ "']/tagname[text()='" +str3+ "']");
-
Console output:
//tagname[text()='stringA']/tagname[text()='stringB']/tagname[text()='stringC']
答案2
得分: 0
以下是翻译好的部分:
假设xpath是“//tagname[text()='param']/tagname[text()='param']/tagname[text()='param']”而param是需要替换的模式。
public static String replaceValue(String xpath, String... params) {
for (String replacement : params) {
xpath = xpath.replaceFirst("param", replacement);
}
return xpath;
}
您还可以在xpath中使用正则表达式模式,而不是'param'关键字。
英文:
Suppose xpath is "//tagname[text()='param']/tagname[text()='param']/tagname[text()='param']" and param is pattern that need to be replaced.
public static String replaceValue(String xpath , String...params){
for(String replacement : params){
xpath = xpath.replaceFirst("param",replacement);
}
return xpath;
}
you also can use a regex pattern instead of 'param' keyword in xpath.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论