I want to select a node based on an attribute value. I am using C# program to derive on the attribute value which is stored in a variable. The below code returns null. How can I compare the attribute value against a variable?

     string posSecond = "test";
     SelectSingleNode("//viewentries/viewentry[@position=posSecond]");

Thanks!

Dani AI

Generated

— the null came from putting the C# variable name directly into the XPath. XPath does not see C# variables; an unquoted token in the predicate is treated as an XPath name/expression, not the runtime string. 's suggestion to build the XPath with the variable value is correct.

A couple of practical notes that often bite later:

  • If the attribute value can contain quotes, a naive string insert will produce invalid XPath.
  • XML namespaces require an XmlNamespaceManager passed into SelectSingleNode/SelectNodes.
  • If the attribute holds numbers and numeric comparison is intended, use a numeric XPath comparison; otherwise compare as strings.
  • For debugging, log the final XPath string before calling SelectSingleNode.

A safe way to insert arbitrary text into an XPath string is to turn the value into a valid XPath literal. The helper below builds a literal that works even when the value contains both single and double quotes:

static string ToXPathLiteral(string value)
{
    if (!value.Contains("'"))
        return "'" + value + "'";
    if (!value.Contains("\""))
        return "\"" + value + "\"";

    var parts = value.Split('\'');
    var sb = new System.Text.StringBuilder();
    sb.Append("concat(");
    for (int i = 0; i < parts.Length; i++)
    {
        if (i > 0) sb.Append(", \"'\", ");
        sb.Append("'" + parts[i] + "'");
    }
    sb.Append(")");
    return sb.ToString();
}

Use the returned literal when building the predicate (and remember to use XmlNamespaceManager if namespaces are present). For untrusted input, escape with this helper to avoid malformed XPath or injection; for large/complex queries consider XPathNavigator + a custom XsltContext to pass variables (advanced).

Recommended Answers

All 2 Replies

SelectSingleNode(string.Format("//viewentries/viewentry[@position='{0}']", posSecond));

should work, assuming the position attribute contains a string value.

Spot on! Yes, the variable is defined as string.
Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.