我使用以下 XPATH Query
列出站点下的对象。 ListObject[@Title='SomeValue']
。 SomeValue 是动态的。只要 SomeValue 没有撇号 (‘),此查询就有效。也尝试使用转义序列。没用。
我究竟做错了什么?
原文由 Prabhu 发布,翻译遵循 CC BY-SA 4.0 许可协议
我将罗伯特的答案移植到 Java(在 1.6 中测试):
/// <summary>
/// Produce an XPath literal equal to the value if possible; if not, produce
/// an XPath expression that will match the value.
///
/// Note that this function will produce very long XPath expressions if a value
/// contains a long run of double quotes.
/// </summary>
/// <param name="value">The value to match.</param>
/// <returns>If the value contains only single or double quotes, an XPath
/// literal equal to the value. If it contains both, an XPath expression,
/// using concat(), that evaluates to the value.</returns>
public static String XPathLiteral(String value) {
if(!value.contains("\"") && !value.contains("'")) {
return "'" + value + "'";
}
// if the value contains only single or double quotes, construct
// an XPath literal
if (!value.contains("\"")) {
System.out.println("Doesn't contain Quotes");
String s = "\"" + value + "\"";
System.out.println(s);
return s;
}
if (!value.contains("'")) {
System.out.println("Doesn't contain apostophes");
String s = "'" + value + "'";
System.out.println(s);
return s;
}
// if the value contains both single and double quotes, construct an
// expression that concatenates all non-double-quote substrings with
// the quotes, e.g.:
//
// concat("foo", '"', "bar")
StringBuilder sb = new StringBuilder();
sb.append("concat(");
String[] substrings = value.split("\"");
for (int i = 0; i < substrings.length; i++) {
boolean needComma = (i > 0);
if (!substrings[i].equals("")) {
if (i > 0) {
sb.append(", ");
}
sb.append("\"");
sb.append(substrings[i]);
sb.append("\"");
needComma = true;
}
if (i < substrings.length - 1) {
if (needComma) {
sb.append(", ");
}
sb.append("'\"'");
}
System.out.println("Step " + i + ": " + sb.toString());
}
//This stuff is because Java is being stupid about splitting strings
if(value.endsWith("\"")) {
sb.append(", '\"'");
}
//The code works if the string ends in a apos
/*else if(value.endsWith("'")) {
sb.append(", \"'\"");
}*/
sb.append(")");
String s = sb.toString();
System.out.println(s);
return s;
}
希望这对某人有帮助!
原文由 Cody S 发布,翻译遵循 CC BY-SA 3.0 许可协议
15 回答8.4k 阅读
8 回答6.2k 阅读
1 回答6k 阅读✓ 已解决
1 回答4k 阅读✓ 已解决
3 回答6k 阅读
3 回答2.2k 阅读✓ 已解决
2 回答3.1k 阅读
这出乎意料地难以做到。
看一下 XPath Recommendation ,您会发现它将文字定义为:
也就是说,XPath 表达式中的字符串文字可以包含撇号或双引号,但不能同时包含两者。
你不能使用转义来解决这个问题。像这样的文字:
将匹配此 XML 文本:
这确实意味着可能存在一段您无法生成 XPath 文字来匹配的 XML 文本,例如:
但这并不意味着不可能将该文本与 XPath 匹配,这只是棘手而已。在您尝试匹配的值同时包含单引号和双引号的任何情况下,您都可以构造一个使用
concat
的表达式来生成要匹配的文本:所以这导致我们这样做,这比我希望的要复杂得多:
是的,我在所有边缘情况下都对其进行了测试。这就是为什么逻辑如此愚蠢地复杂: