diff options
Diffstat (limited to 'common')
-rw-r--r-- | common/src/com/android/utils/XmlUtils.java | 21 | ||||
-rw-r--r-- | common/tests/src/com/android/utils/XmlUtilsTest.java | 5 |
2 files changed, 25 insertions, 1 deletions
diff --git a/common/src/com/android/utils/XmlUtils.java b/common/src/com/android/utils/XmlUtils.java index 73e1d11..94b7405 100644 --- a/common/src/com/android/utils/XmlUtils.java +++ b/common/src/com/android/utils/XmlUtils.java @@ -182,6 +182,27 @@ public class XmlUtils { } /** + * Converts the given attribute value to an XML-text-safe value, meaning that + * less than and ampersand characters are escaped. + * + * @param textValue the text value to be escaped + * @return the escaped value + */ + @NonNull + public static String toXmlTextValue(@NonNull String textValue) { + for (int i = 0, n = textValue.length(); i < n; i++) { + char c = textValue.charAt(i); + if (c == '<' || c == '&') { + StringBuilder sb = new StringBuilder(2 * textValue.length()); + appendXmlTextValue(sb, textValue); + return sb.toString(); + } + } + + return textValue; + } + + /** * Appends text to the given {@link StringBuilder} and escapes it as required for a * DOM attribute node. * diff --git a/common/tests/src/com/android/utils/XmlUtilsTest.java b/common/tests/src/com/android/utils/XmlUtilsTest.java index 6c28451..ea33346 100644 --- a/common/tests/src/com/android/utils/XmlUtilsTest.java +++ b/common/tests/src/com/android/utils/XmlUtilsTest.java @@ -16,7 +16,6 @@ package com.android.utils; import com.android.SdkConstants; -import com.android.utils.XmlUtils; import org.w3c.dom.Attr; import org.w3c.dom.Document; @@ -79,6 +78,10 @@ public class XmlUtilsTest extends TestCase { assertEquals("<"'>&", sb.toString()); } + public void testToXmlTextValue() throws Exception { + assertEquals("<\"'>&", XmlUtils.toXmlTextValue("<\"'>&")); + } + public void testAppendXmlTextValue() throws Exception { StringBuilder sb = new StringBuilder(); XmlUtils.appendXmlTextValue(sb, "<\"'>&"); |