How to use XPath-Functions like exists() in C#?

1.8k Views Asked by At

I want to read some Nodes from a XmlDocument-Object using the SelectNodes-Method and the XPathNavigator-Class.

But C# is unable to evaluate this (validated with XMLSpy) XPath-Expressen:

//LogicUnit[exists(Level[@val = 'R'])]/LogicLines[exists(LogicLine/DATAVIEW_SRC)]

The Runtime throws the XPAthException "Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function."

I don't understand this exception because my XML-Document doesn't use any Namespaces and there is also no XSLT-Document. This exception always appears if I'm using any XPATH-function.

3

There are 3 best solutions below

1
On BEST ANSWER

The reason is that it can't use functions without a namespace manager, however, you don't need to use functions, and your code is using that function in the wrong way. you don't need the function exists() to see if something exists, from what I see you are using

//LogicUnit[exists(Level[@val = 'R'])]

where you mean

//LogicUnit[Level[@val = 'R']]
1
On

Use //LogicUnit[count(Level[@val = 'R']) > 0].

0
On

The XPath function exists() is defined in XPath 2.0, but the default Microsoft XPath engine in .NET only supports XPath 1.0. If you want an XPath 2.0 engine that runs under .NET, try Saxon or XQSharp.