Find the index of an xml element in text C#

I am making a WPF app which displays XML in a FlowDocument, and a user can select an element or elements in this XML with XPath. I want to be able to highlight the value of the element that the XPath is selecting in the FlowDocument. I am currently looking at highlighting using this method. The problem is that since the FlowDocument displays a string, I need to find the index of any element(s) that the XPath represents in this string - I can't simply just search for it as text as it could produce false matches. Any suggestions how I can do this?

Jon Skeet
people
quotationmark

If you're happy to use LINQ to XML instead (it's a generally nicer API) and if knowing the line number and position within the line is good enough, you could use IXmlLineInfo:

using System;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;

class Program
{
    static void Main(string[] args)
    {
        var xml = XDocument.Load("test.xml", LoadOptions.SetLineInfo);
        var xpath = "/root/child";
        var result = xml.XPathSelectElements(xpath);
        foreach (var element in result)
        {
            var info = (IXmlLineInfo) element;
            Console.WriteLine("{0}:{1} {2}",
                              info.LineNumber,
                              info.LinePosition,
                              element);
        }
    }
}

It's entirely possible that you can use this with XmlElement as well, but I'm not sure how. This doesn't give you the character position, of course - but aside from anything else, you could work out the character location of the start of each line yourself reasonably easily. There may be something else to specify the exact character location, of course - I just haven't seen it.

people

See more on this question at Stackoverflow