如果是XPath表達式你擔心的只是可讀性,你可以抽象是走一點點:
var keyword = "A Keyword";
var nodes1 = xmlDoc.SelectNodes(String.Format("//foo[{0}]", XPathValueContains(keyword)));
var nodes2 = xmlDoc.SelectNodes(String.Format("//foo[{0}]", XPathValueEquals(keyword)));
其中XPathValueContains()
和XPathValueEquals()
是:
public static string XPathValueContains(string input)
{
return String.Format(
"contains(translate(., {0}, {1}), {1})",
XPathEscapeString(input.ToUpperInvariant()),
XPathEscapeString(input.ToLowerInvariant())
);
}
public static string XPathValueEquals(string input)
{
return String.Format(
"translate(., {0}, {1}) = {1}",
XPathEscapeString(input.ToUpperInvariant()),
XPathEscapeString(input.ToLowerInvariant())
);
}
和XPathEscapeString()
一個函數來處理嵌入式單引號,定義如下:
public static string XPathEscapeString(string input)
{
if (input.Contains("'"))
{
return "concat('" + String.Join("', \"'\", '", input.Split('\'')) + "')";
}
else
{
return "'" + input + "'";
}
}
* *爲什麼你要這麼做? – Tomalak 2012-03-16 06:27:46
我想在文檔內容上運行不區分大小寫的xpath查詢,而不必一直使用翻譯功能 – 2012-03-16 06:31:08
我一直這麼想。你是否有一個實際的性能瓶頸? – Tomalak 2012-03-16 06:36:44