Java String Sanitize sanitizeStringForXPath(String text)

Here you can find the source of sanitizeStringForXPath(String text)

Description

Convert the string to a safer version for XPath For example: Will o' The Wisp => concat('Will o' , "'" , ' The Wisp' , '') This will result in the same string when read by XPath.

License

Open Source License

Return

safer version of the text for XPath

Declaration

public static String sanitizeStringForXPath(String text) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**// w  ww .j  a v  a 2  s .  co  m
     * Convert the string to a safer version for XPath
     * For example:
     * Will o' The Wisp => concat('Will o' , "'" , ' The Wisp' , '')
     * This will result in the same string when read by XPath.
     *
     * <p>This is used when writing the test case for some special characters
     * such as ' and "
     *
     * @return safer version of the text for XPath
     */
    public static String sanitizeStringForXPath(String text) {
        StringBuilder result = new StringBuilder();
        int startOfChain = 0;
        int textLength = text.length();
        boolean isSingleQuotationChain = false;
        // currentPos iterates one position beyond text length to include last chain
        for (int currentPos = 0; currentPos <= textLength; currentPos++) {
            boolean isChainBroken = currentPos >= textLength
                    || isSingleQuotationChain
                    && text.charAt(currentPos) != '\''
                    || !isSingleQuotationChain
                    && text.charAt(currentPos) == '\'';
            if (isChainBroken && startOfChain < currentPos) {
                // format text.substring(startOfChain, currentPos) and append to result
                char wrapper = isSingleQuotationChain ? '\"' : '\'';
                result.append(wrapper)
                        .append(text.substring(startOfChain, currentPos))
                        .append(wrapper).append(',');
                startOfChain = currentPos;
            }
            // flip isSingleQuotationChain if chain is broken
            if (isChainBroken) {
                isSingleQuotationChain = !isSingleQuotationChain;
            }
        }
        if (result.length() == 0) {
            return "''";
        }
        return "concat(" + result.toString() + "'')";
    }
}

Related

  1. sanitizeString(String s)
  2. sanitizeString(String s)
  3. sanitizeString(String s)
  4. sanitizeString(String str)
  5. sanitizeStringAsLiteral(String literal)
  6. sanitizeStringLiteral(String inputString)
  7. sanitizeSuiteName(String name)
  8. sanitizeTag(String s)
  9. sanitizeTextAsDomId(final String text)