Encoding XPath Expressions with both single and double quotes

前端 未结 8 1193
孤街浪徒
孤街浪徒 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 08:17

    I was in need of this so I created this solution, for C#.

        /// 
        /// Returns a valid XPath statement to use for searching attribute values regardless of 's or "s
        /// 
        /// Attribute value to parse
        /// Parsed attribute value in concat() if needed
        public static string GetXpathStringForAttributeValue(string attributeValue)
        {
            bool hasApos = attributeValue.Contains("'");
            bool hasQuote = attributeValue.Contains("\"");
    
            if (!hasApos)
            {
                return "'" + attributeValue + "'";
            }
            if (!hasQuote)
            {
                return "\"" + attributeValue + "\"";
            }
    
            StringBuilder result = new StringBuilder("concat(");
            StringBuilder currentArgument = new StringBuilder();
            for (int pos = 0; pos < attributeValue.Length; pos++)
            {
                switch (attributeValue[pos])
                {
                    case '\'':
                        result.Append('\"');
                        result.Append(currentArgument.ToString());
                        result.Append("'\",");
                        currentArgument.Length = 0;
                        break;
                    case '\"':
                        result.Append('\'');
                        result.Append(currentArgument.ToString());
                        result.Append("\"\',");
                        currentArgument.Length = 0;
                        break;
                    default:
                        currentArgument.Append(attributeValue[pos]);
                        break;
                }
            }
            if (currentArgument.Length == 0)
            {
                result[result.Length - 1] = ')';
            }
            else
            {
                result.Append("'");
                result.Append(currentArgument.ToString());
                result.Append("')");
            }
            return result.ToString();
        }
    

提交回复
热议问题