user1373355
user1373355

Reputation: 33

Xpath error has an Invalid Token

I have the following C# code:

var selectNode = xmlDoc.SelectSingleNode("//CodeType[@name='" + codetype + 
    "']/Section[@title='" + section + "']/Code[@code='" + code + "' and 
    @description='" + codedesc + "']") as XmlElement;

when I run my code it raises the error saying "the above statement has an invalid token"

These are the values for the above statement.

codeType=cbc
section="Mental"
codedesc="Injection, enzyme (eg, collagenase), palmar fascial cord (ie, 
    Dupuytren's contracture"

Upvotes: 3

Views: 34039

Answers (3)

Jai Govind Gupta
Jai Govind Gupta

Reputation: 95

You can get selected node based on index , if any special characters in the xml schema. So , here looks below implementation for delete selected index node from xml schema.

XML SelectSingleNode Delete Operation

var schemaDocument = new XmlDocument();

        schemaDocument.LoadXml(codesXML);

        var xmlNameSpaceManager = new XmlNamespaceManager(schemaDocument.NameTable);

        if (schemaDocument.DocumentElement != null)
            xmlNameSpaceManager.AddNamespace("x", schemaDocument.DocumentElement.NamespaceURI);

        var codesNode = schemaDocument.SelectSingleNode(@"/x:integration-engine-codes/x:code-categories/x:code-category/x:codes", xmlNameSpaceManager);
        var codeNode = codesNode.ChildNodes.Item(Convert.ToInt32(index) - 1);

        if (codeNode == null || codeNode.ParentNode == null)
        {
            throw new Exception("Invalid node found");
        }

        codesNode.RemoveChild(codeNode);
        return schemaDocument.OuterXml;

Upvotes: 1

MGV
MGV

Reputation: 5

Duplicate the single quote, so that it reads "Dupuytren''s contracture"

This way you can escape the single quote in the xpath expression.

Upvotes: -3

Cristian Lupascu
Cristian Lupascu

Reputation: 40506

Notice the apostrophe (') in codedesc?

You need to escape it somehow. The XPath interpreter considers it as a string delimiter and doesn't know how to treat the other apostrophe after it.

One way you can do that is by enclosing your string in double quotes instead of apostrophes.

Your code could therefore become:

var selectNode = xmlDoc.SelectSingleNode(
    "//CodeType[@name='" + codetype + "']" +
    "/Section[@title='" + section + "']" +
    "/Code[@code=\"" + code + "' and @description='" + codedesc + "\"]") 
    as XmlElement;

(note that on the fourth line, the apostrophes(') became double quotes(\"))

While this approach works for the data you presented, you are still not 100% safe: other records could contain double quotes themselves. If that happens, we'll need to think of something for that case as well.

Upvotes: 7

Related Questions