3

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"
4

3 に答える 3

7

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.

于 2012-05-03T19:36:03.673 に答える
1

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;
于 2019-06-12T10:57:47.667 に答える
-3

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

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

于 2014-07-16T21:02:32.477 に答える