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:

1
2
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:

Hope this complex example clarifies some questions about XPATH.

comments powered by Disqus