Parse your XML with XPATH and find a value of an element based on the value of another element

When parsing and reading XML files in your C# code, you can use the XDocument or XElement objects to access it with LINQ and the Descendants or Elements properties. However, there is another option; you can use XPATH for traversing the XML. In this example we are going to see how you access a value of an XML-element, by matching the value of another element with a value given from the user.

Here is the code:

string? valueAsString = xElement.XPathEvaluate(
            string.Format("string(//*[name()='a:FooElement'][*[name()='a:MatchElement']='{0}']/*[name()='a:SearchedElement'])", userInputString)) as string;

And here is the more detailed explanation of the code: - The //* its a wildcard for selecting all elements in the document - We then search for the elements with the name FooElement. For that, we explicitly use the name() attribute, because our XML can contain namespaces in it and we to select only the name of the element - Next we match the MatchElement with the user input, with the help of string.Format. Pay attention in how we use the * wildcard - Finally with /* we are selecting from the route node, in that case FooElement, the SearchedElement - With the string() which wraps our XPATH expression, we are selecting the value found in the previous step - We finally cast the result to string, since XPathEvaluate returns an object

Hope this complex example clarifies some questions about XPATH.

comments powered by Disqus