Groups | Blog | Home
all groups > dotnet xml > september 2003 >

dotnet xml : Prepare String for XPath



Matthew Wieder
9/25/2003 11:17:09 AM
Does someone have the routine (preferablly in C#) that takes a string
(i.e. "3995 Joseph, Smith "Joe") and prepares it for use in an XPath
query ( i.e. SelectSingleNode(/member[@name=concat("3995 Joseph, Smith
", '"', "Joe"]) ) so that all escape characters are taken care of and
the issue with not having single and double quotes in the string is also
taken care of? I'm sure many people must have hit this issue; I don't
want to re-invent the wheel if I don't have to.
thanks!
Joe Feser
9/25/2003 11:35:03 AM
Wouldn't it be even cooler if the item worked like SqlParameters where you
could define a parameter like @name and then add a parameters to the
SelectSingleNode.Parameters collection and let the CLR figure out the mess.
:)

I don't have a function but i run across the same problems.

It also seems dependent on if you use single ' or double " to enclose the
text.

if you use " you don't need to encode the '....

It is very frustrating to have to debug.

My two cents.

Joe Feser

[quoted text, click to view]

Matthew Wieder
9/25/2003 2:21:38 PM
To save someone else the trouble, here's the code (in C#):
//this method takes a string used as an attribute of and XPath query and
handles quotation marks as neccesary
private string PrepXPathString(string strInput)
{
string[] saParts;
string strOutput;

saParts = strInput.Split("\"".ToCharArray());

//string contains no quotes so only need to wrap in quotes
if (saParts.Length == 1)
{
strOutput = "\"" + strInput + "\"";;
}
else
{
strOutput = "concat(";
strOutput+= "\"" + saParts[0] + "\"";

for (int i=1; i<saParts.Length; i++)
{
strOutput+= ",'\"',";
strOutput+= "\"" + saParts[i] + "\"";
}

strOutput+= ")";
}

return strOutput;
}

[quoted text, click to view]
AddThis Social Bookmark Button