Handling Apostrophe (single-quote) in XPath expressions in .NET

October 4, 2007

If you are playing with XML using .NET libraries, then you might be familiar with below mentioned exception:
System.Xml.XPath.XPathException: ‘objOfXmlDocument[@attribute={value containing single-quote}]‘ has an invalid token.
If you are looking for a patch for the above mentioned problem, then you are at the right place.
Sample xml text: //test.xml
<?xml version=”1.0″ encoding=”utf-8″ ?>
<
root>
<
emp fname=”Vaibhav” lname=”Gaikwad” />
<
emp fname=”Lavina” lname=”D’cunha” />
</
root>
//code to access the test.xml
class
Program
{
static void Main(string[] args) {
XmlDocument doc = new XmlDocument();
doc.Load(
“test.xml”);
string ln =
“D’cunha”;
// This fails :((  resulting in XPath exception.
XmlNode n = doc.SelectSingleNode(“/root/emp[@lname=’ “+ ln +” ‘]”);
}
}  
So, the issue is due the single-quote inside the XPath expression.
We try to resolve it using the “concat” function of XSL, and this is the helper function:
public static string GetXPathString(string input) {
string[] fragments = input.Split(new char[] { ‘\” });
string result = “”;
result += “concat(””;
for (int i = 0; i < fragments.Length; i++)
{
result += “, ‘” + fragments[i] + “‘”;
if (i < fragments.Length – 1)
{
result += “, \”‘\””;
}
}
result += “)”;
return result;
}
And here is how you modify the above code so as to use our new function:
// remember to remove the single-quotes after = and ]
 
XmlNode n = doc.SelectSingleNode(“/root/emp[@lname=” + GetXPathString(ln) + “]”);
So its all done and the day is saved.

 -Bugs!

About these ads

7 Responses to “Handling Apostrophe (single-quote) in XPath expressions in .NET”

  1. Kiran Patil Says:

    Thanks a lot dude..it had helped me a lot for my project also and it also helped my one[or more days..]..thanx again from hear.. But i faced one problem which is using it directly because it creates problem because of syntax because it dosen’t differs “” and ‘ ‘ so i am posting code in C# Here:
    —————————————————-
    private static string GetXpathString(string input)
    {

    string[] fragments = input.Split(new char[] {‘\”});
    string result=””;
    result+=”concat(””;
    for (int i = 0; i < fragments.Length; i++)
    {
    result+= “,’”+fragments[i]+”‘”;
    if(i<fragments.Length-1)
    {
    result+=”,\”‘\””;
    }
    }
    result+=”)”;
    return result;
    }

    —————————————————
    And i need to put it in VB.NET so it’s also here
    —————————————————
    Private Shared Function GetXpathString(ByVal input As String) As String
    Dim fragments As String() = input.Split(New Char() {“‘”c})
    Dim result As String = “”
    result += “concat(””
    For i As Integer = 0 To fragments.Length – 1
    result += “,’” + fragments(i) + “‘”
    If i < fragments.Length – 1 Then
    result += “,””‘”””
    End If
    Next
    result += “)”
    Return result
    End Function
    —————————————————

    Tahedil se Shukriya..
    From: KIran Patil(sw.engineer.NET)

  2. Richard Cranium Says:

    Try to implement your solution above but does not seem to work. Can you provide an input and result so that I debug? For example, I’m trying to use “Mss: (AFD Max… ‘quasi-free’ connections..” as input to a selectsinglenode(“./something/somethingelse[@attrib=return]“); this causes an ‘The expression passed to this method should result in a NodeSet.” exception.

    Thanks

  3. Vaibhav Says:

    Hi Richard,
    I am wondering why it does not work in your case. Can you send me the test xml file, and also let me the node which you are trying to read. I’ll try to send you the test implementation as soon as possible.

    Thanks for the response.

    -Bugs!

  4. purushoth12 Says:

    thanks for ur post. My need was in C#.

    The Single quote escape in XPATH C# gave me readymade function to solve the issue.

  5. pentalogic Says:

    Mr Bugs – you are making hard work of that I think. If you only have to deal with ‘ OR ” you can just use something like

    // C#
    XmlNode n = doc.SelectSingleNode(“/root/emp[@lname=\"D'cunha\""]

    // VB.NET
    XmlNode n = doc.SelectSingleNode(“/root/emp[@lname=""D'cunha"""]

    If you have to deal with BOTH ‘ and ” then you have to use concat.

    See http://stackoverflow.com/questions/642125/encoding-xpath-expressions-with-both-single-and-double-quotes

  6. pentalogic Says:

    Seen that wordpress does something strange with quotes – ” so if you copy this into Visual Studio then you might have to replace with the correct quote char.


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: