Proposed Answer Escape character in Xpath

  • Wednesday, February 08, 2012 1:00 PM
     
     

    Hi

    I'm getting this error ""Expected token ']' found 'NAME'" mainly because the xpath query that I'm using contains a special character - single quote ex: xpath = \[@source=men's] and I'm using MSXML2 xpath for parsing. How do we escape such special characters in VB.Net? This is a upgraded project from VB6.

    Thanks

All Replies

  • Wednesday, February 08, 2012 1:16 PM
     
     Proposed Answer Has Code

    First of all with .NET you shouldn't use MSXML at all, instead you should use the pure managed XML and XPath classes in System.Xml and System.Xml.XPath.

    As for the XPath syntax, XPath 1.0 (which is what both MSXML and .NET support) does not have an escape mechanism for quotes so the only approach you have is alternating double and single quotes as long as possible e.g.

            Dim xml As String = "<root><foo source=""men's""/></root>"
            Dim value As String = "men's"
            Dim doc As New XmlDocument()
            doc.LoadXml(xml)
            For Each foo As XmlElement In doc.SelectNodes(String.Format("//foo[@source = ""{0}""]", value))
                Console.WriteLine(foo.OuterXml)
            Next

    If you still have problems then please post the exact code.


    MVP Data Platform Development My blog