0

Is there a method in Saxon, or another library, that will tell me if an XPath query is valid syntax. Not if it will return something, not if the nodes exist in an XML file, but if it's valid syntax.

I need to use this to determine if a query is XPath vs an equation we handle ourselves.

thanks - dave

David Thielen
  • 28,723
  • 34
  • 119
  • 193
  • [This method](https://www.saxonica.com/html/documentation/javadoc/net/sf/saxon/s9api/XPathCompiler.html#compile-java.lang.String-) throws exception if the expression cannot be compiled. – LMC Jan 26 '18 at 23:52

1 Answers1

2

Your best bet is to call XPathCompiler.compile() and catch the exception. I know you're concerned about the cost of exceptions, but there's no way of doing this in Saxon without exceptions.

Note that the phrase "valid syntax" needs qualification. The compile() method will not only check syntax, it will also check for other static errors such as references to variables and functions that don't exist. You can influence this checking by supplying a suitable static context for the parsing.

Michael Kay
  • 156,231
  • 11
  • 92
  • 164
  • Unfortunately IKVM makes this approach dog slow. Have you considered a TryParse (like C# has for parsing numbers, etc)? – David Thielen Jan 28 '18 at 22:12
  • Unfortunately it would be a pretty substantial rewrite of the parser (which is rather larger than a parser for numbers!) to meet what is definitely a rather specialised requirement. – Michael Kay Jan 29 '18 at 09:26
  • Yeah, I had a bad feeling that's the case. What about a likelyXPath() method? Or is that something that would just get us in trouble? – David Thielen Jan 29 '18 at 16:32
  • The thread at https://stackoverflow.com/questions/36343209/which-part-of-throwing-an-exception-is-expensive suggests a different way forward: throw an exception that doesn't contain a stack trace, which is much cheaper. But that information is all specific to Java, I've no idea how it carries over to code cross-compiled by IKVM to .NET. – Michael Kay Jan 30 '18 at 00:21