Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xpath error has an Invalid Token

Tags:

c#

xml

xpath

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"
like image 598
user1373355 Avatar asked May 26 '26 16:05

user1373355


2 Answers

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.

like image 61
Cristian Lupascu Avatar answered May 28 '26 16:05

Cristian Lupascu


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;
like image 25
Jai Govind Gupta Avatar answered May 28 '26 15:05

Jai Govind Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!