aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorKevin Jin <kjin@google.com>2013-07-10 15:32:02 -0700
committerKevin Jin <kjin@google.com>2013-07-10 15:32:02 -0700
commitd88d4ab289d47627418aa500d43b9c11168acba7 (patch)
tree8e1e5b381141f1837cbeb6cceb5502c41b53d8f6
parentc91cb19438c6ef8ecd794664bf1f879725866bb9 (diff)
downloaddroiddriver-d88d4ab289d47627418aa500d43b9c11168acba7.tar.gz
add XPaths.quoteXPathLiteral
Change-Id: I682f2493a49db26f8092ae8bb8c5267f0c58bfc3
-rw-r--r--src/com/google/android/droiddriver/finders/XPaths.java36
1 files changed, 34 insertions, 2 deletions
diff --git a/src/com/google/android/droiddriver/finders/XPaths.java b/src/com/google/android/droiddriver/finders/XPaths.java
index d1be75f..7453585 100644
--- a/src/com/google/android/droiddriver/finders/XPaths.java
+++ b/src/com/google/android/droiddriver/finders/XPaths.java
@@ -16,6 +16,8 @@
package com.google.android.droiddriver.finders;
+import com.google.common.base.Joiner;
+
/**
* Convenience methods and constants for XPath.
* <p>
@@ -78,16 +80,46 @@ public class XPaths {
/** @return XPath predicate (with enclosing []) for attribute with value */
public static String attr(Attribute attribute, String value) {
- return String.format("[@%s='%s']", attribute.getName(), value);
+ return String.format("[@%s=%s]", attribute.getName(), quoteXPathLiteral(value));
}
/** @return XPath predicate (with enclosing []) for attribute containing value */
public static String containsAttr(Attribute attribute, String containedValue) {
- return String.format("[contains(@%s, '%s')]", attribute.getName(), containedValue);
+ return String.format("[contains(@%s, %s)]", attribute.getName(),
+ quoteXPathLiteral(containedValue));
}
/** Shorthand for {@link #attr}{@code (Attribute.TEXT, value)} */
public static String text(String value) {
return attr(Attribute.TEXT, value);
}
+
+ /**
+ * Adapted from http://stackoverflow.com/questions/1341847/.
+ * <p>
+ * 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.
+ */
+ private static String quoteXPathLiteral(String value) {
+ // if the value contains only single or double quotes, construct an XPath
+ // literal
+ if (!value.contains("\"")) {
+ return "\"" + value + "\"";
+ }
+ if (!value.contains("'")) {
+ return "'" + value + "'";
+ }
+
+ // 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(\"");
+ Joiner.on("\",'\"',\"").appendTo(sb, value.split("\""));
+ sb.append("\")");
+ return sb.toString();
+ }
}