1

I am trying to evaluate an XPath expression which contains the function format-number within the C# method XPathEvaluate(XNode, String). A simplified reproduction is as follows:

// In this example, the XML is not actually used; written purely to demonstrate the issue
XElement test =  new XElement("test", 12);
object output = test.XPathEvaluate("format-number(2, \"00\")");

When this runs, the following exception is thrown:

System.Xml.XPath.XPathException: 'Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function.'

I have tried to add the XSLT namespace to an XmlNamespaceManager which is then provided to the XPathEvaluate function, as suggested by the exception message and in an answer to a similar question, but that also did not work:

var manager = new XmlNamespaceManager(new NameTable());
manager.AddNamespace("xsl", "http://www.w3.org/1999/XSL/Transform");
test.XPathEvaluate("format-number(2, \"00\")", manager);

How can I call the format-number function within an XPath statement?

Andrew Bennet
  • 2,600
  • 1
  • 21
  • 55
  • 1
    Microsoft only offers XSLT and XPath 1 support where `format-number` is an XSLT only function not exposed to XPath. In actual versions of XPath https://www.w3.org/TR/xpath-functions/#func-format-number the function is also available to XPath so if you use a third party library like Saxon 9 you can use XPath 3 and `format-number`, although I don't think they offer that for the LINQ to XML object model with `XElement`, only for the DOM `XmlElement`. – Martin Honnen Mar 28 '18 at 14:52
  • Ah, interesting. I was able to use `format-number` in XSLT 1.0 invoked from a .NET application, so assumed it should work via the C# also. – Andrew Bennet Mar 28 '18 at 14:59
  • @MartinHonnen, your English is superb but you have fallen into a translation trap: "Aktuell" does not translate into "Actual". You mean "current versions". – Michael Kay Mar 29 '18 at 08:31

1 Answers1

2

Unfortunately, format-number function is not supported by MS XPath. It doesn't contain a lot of functions of XSLT. You can find all supporting functions in picture from post here.

But you can have to create your own function here. In article from above you can found my 3 function examples (if-else, format and current).

Sorry, my native language is Russian, but there is translation button. So, you need only take a look on the 1st image and check example code from the first download link. I hope you can copy code and implement your needed functionality for format-number.

Sergey Vaulin
  • 722
  • 4
  • 16