Codingday
Codingday

Reputation: 855

SelectSingleNode to Evaluate LowerCase NodeSet value

I am trying to get the value of an xpath expression in lower case using SelectSingleNode, is there an Xpath that can give me the lower case value of an evaluated xpath expression?

It is possible by having a xsl transform sheet, but is it possible with below?

The function expects to have nodeset type, below evaluates to string thus it throws exception. Is it possible to convert the returning string to a nodeset to make SelectSingleNode happy

        string xml = "<bac><test>Val</test></bac>";
        string xpath = "/bac/test/text()";

        var transpath = "translate(/bac/test/text(),'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')";

        StringReader sReader = new StringReader(xml);

        XmlReader xReader = new XmlTextReader(sReader);            
        XPathDocument xmlPathDoc = new XPathDocument(xReader);
        XPathNavigator nav = xmlPathDoc.CreateNavigator();

        XPathNodeIterator nodeIterator = nav.Select("/");

        XPathNavigator navNode = nodeIterator.Current;
        var v = navNode.SelectSingleNode(transpath).Value;
       // expect val 

Upvotes: 0

Views: 457

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167716

If you have an XPath expression that returns a primitive value (string, number, boolean) instead of a set of nodes you need to use the Evaluate method on XPathNavigator, see http://msdn.microsoft.com/en-us/library/2c16b7x8.aspx.

So for your code you could simplify it to

    string xml = "<bac><test>Val</test></bac>";
    string xpath = "/bac/test";

    var transpath = "translate(/bac/test,'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')";

     XPathNavigator nav;
     using (StringReader sr = new StringReader(xml))
     {
        nav = new XPathDocument(sr).CreateNavigator();
     }
     string v = nav.Evaluate(transpath) as string;

On the other hand .NET is stronger on string operations than XPath 1.0 is so I would be tempted to use

 XPathNavigator test = nav.SelectSingleNode(path);
 string v = test.Value.ToLower();

Upvotes: 1

Related Questions