SelectSingleNode XPATH to match single quoted data

I am using the XmlDocument class to query XML data with XPATH.

Some of my data includes single quote characters. For example:

<menuitem>S/CData.XYZ.Submissions.S/C's</menuitem>

How do I match on this data with XPATH within a SelectSingleNode method call I have tended to use single quotes to encapsulate string data within XPATH queries. For example:

XmlNode test = DOM.SelectSingleNode(customer[@name='fred']);

However, this obviously does not work when the data itself contains single quotes.

I modified my approach to encapsulate the string data to match in XPATH within double quotes.

string matchText = "S/CData.XYZ.Submissions.S/C's";

XmlNode assignedMenuItem =
menuData.SelectSingleNode(@"menuitem[.="""
+ matchText + @"""]");

Is this the best solution Or can the data to search for be escaped, while still allowing the appropriate match



Answer this question

SelectSingleNode XPATH to match single quoted data

  • jstfsklh211

    You can construct the string with XPath expression differently but in any case it will be somehow ugly.

    Things become even worse when text you'd like to compare has both ' and " .

    In XSLT you can construct such text in the variable and then have:

    <xsl:value-of select="menuitem[.=$var]"/>

    In DOM you also can do such trick by providing XslContext for your XPathExpression. But this will be to much of hassle for this problem.



  • bolky

    I would have thought this was fairly common problem, particularly where the data contains single quotes. How should single and double quotes within the XML data be handled within an XPATH query via the DOM Or how do I use the XsltContext with the DOM
  • SelectSingleNode XPATH to match single quoted data