Search code examples
c#xpathxmldocument

XPath find all matches C# XmlDocument


I am trying to figure out how to find all matches of string in a XmlDocument.

XmlNodeList results 
      = document.SelectNodes("Products/Product/fn:matches(.,'" + SearchWord + "')");

Im trying to compare the innerText of Product.

The above example don't work though, but I guess my way of using XPath functions are very wrong.


Solution

  • Evaluate this XPath 1.0 expression (did you know matches() is an XPath 2.0 function and isn't supported in .NET):

    Products/Product/descendant::*[contains(text(), 'YourSearchWord')]
    

    This selects all elements that have a text-node-child that contains the string 'YourSearchWord' and that are descendents of a Product element that is a child of a Products element that is a child of the current (context) node.

    You can compose the XPath expression with:

    string.Format("Products/Product/descendant::*[contains(text(), '{0}')]", 
                  SearchWord )
    

    However, if SearchWord is obtained from user input, it is recommended never to include it in a skeletal string as above, so that XPath injection will be avoided.

    If this is the case, the recommended method is to have a precompiled XPath expression in which the user input will be referenced as a variable and the value of this variable will be consumed from the XPath evaluation context.

    More details how to prevent an XPath injection can be found in this answer:

    https://stackoverflow.com/a/6393690/36305