The preferred way to protect against XPath injection is to utilise
parameterized (also known as prepared) XPath queries. When utilising
this method of querying the XML document any value supplied by the
client will be handled as a string rather than part of the XPath
query.

An alternative to parameterized queries it to use precompiled
XPath queries. Precompiled XPath queries are not generated dynamically
and will therefor never process user supplied input as XPath.