Anthony Serdyukov
Anthony Serdyukov

Reputation: 4328

Check whether XML satisfies user-supplied predicate

Came from Declare namespaces within XPath expression

Simplified task:

What technology should I use for for this task in .NET 3.5 without using third-party libraries?

Candidates:

Update:

I have realized that actually the question is: Is there a way except XPath?

Schematron is the only suggestion at the moment.

Upvotes: 0

Views: 97

Answers (3)

Mads Hansen
Mads Hansen

Reputation: 66714

If the namespaces are an "issue", you could always:

  1. Pre-process the XML files using a modified identity transform to generate an XML file with nodes that are not bound to a particular namespace
  2. Then evaluate the user provided XPATH against the modified XML
  3. Return the result

Do note that while this makes the XPATH creation and evaluation more simple, it completely circumvents the reason for namespaces and you may get ambiguous matches for elements/attributes from another namespace, and return incorrect results.

Upvotes: 0

Michael Kay
Michael Kay

Reputation: 163262

The constraint "without using third-party libraries" seems an odd one: most people these days are trying to maximize code reuse.

Without that constraints, I would say Schematron is the answer. It does exactly what you are looking for.

It's also possible to achieve the same effect using an XSLT stylesheet to define the validation rules - but you end up reinventing Schematron.

Upvotes: 1

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243459

Simplified task:

•There is a lot of XML files of different structure with namespaces

•User defines several predicates in a text form

•The predicates are applied to each XML file giving the result: yes or no

It is not clear what the word "predicates" is intended to mean in the above description.

I assume that this means: "XPath expression(s) that evaluate to boolean"

If this is so, each such individual expression can be evaluated using for example XPathNavigator.Evaluate(XPathExpression)

The problem of different users using different namespaces needs a centralized solution. One approach, which I recommend is to create and publish a central catalog of namespace prefix to namespace mappings, so that the expression-authors should only use prefixes from this catalogue. All these prefixes will be bound to the respective namespaces before evaluating any XPath expression. The .NET class XmlNamespaceManager is very suitable for this purpose. An example how to use XmlNamespaceManager together with XpathNavigator.Evaluate() and XPathNavigator.Select() can be found here.

Very important: Never evaluate strings containing an XPath expression -- this may result in XPath injection. Always compile the string (for exmple using XPathExpression.Compile()). Even if such discipline is adhered to, evaluating an user-supplied XPath expression may lead to security risks.

Upvotes: 1

Related Questions