Encoding XPath Expressions with both single and double quotes

前端 未结 8 1184
孤街浪徒
孤街浪徒 2020-11-30 07:21

XPath (v1) contains no way to encode expressions.

If you only have single OR double quotes then you can use expressions such as

//review[@name=\"Bob         


        
8条回答
  •  一生所求
    2020-11-30 07:59

    Another variation...my concat() part is a little lazy, but at least it uses the whole value.

        /// 
        /// Returns an XPath string literal to use for searching attribute values (wraped in apostrophes, quotes, or as a concat function).
        /// 
        /// Attribute value to encode and wrap.
        public static string CreateXpathLiteral(string attributeValue)
        {
            if (!attributeValue.Contains("\""))
            {
                // if we don't have any quotes, then wrap string in quotes...
                return string.Format("\"{0}\"", attributeValue);
            }
            else if (!attributeValue.Contains("'"))
            {
                // if we have some quotes, but no apostrophes, then wrap in apostrophes...
                return string.Format("'{0}'", attributeValue);
            }
            else
            {
                // must use concat so the literal in the XPath will find a match...
                return string.Format("concat(\"{0}\")", attributeValue.Replace("\"", "\",'\"',\""));
            }
        }
    

提交回复
热议问题