How to prevent XPath/XML injection in .NET

The main idea in preventing an XPath injection is to pre-compile the XPath expression you want to use and to allow variables (parameters) in it, which during the evaluation process will be substituted by user-entered values.

In .NET:

  1. Have your XPath expresion pre-compiled with XPathExpression.Compile().

  2. Use the XPathExpression.SetContext() Method to specify as context an XsltContext object that resolves some specific variables to the user-entered values.

You can read more about how to evaluate an XPath expression that contains variables here.

This text contains good and complete examples.

Leave a Comment