The following code contains all the sheet elements in the document and for each displays an XPath expression that will unambiguously move through the element from the document root, including the predicate at each node step, to disambiguate between elements with the same name:
static void Main(string[] arguments) { XDocument d = XDocument.Load("xmlfile1.xml"); foreach (XElement e in d.XPathSelectElements("//*[not(*)]")) { Console.WriteLine("/" + string.Join("/", e.XPathSelectElements("ancestor-or-self::*") .Select(x => x.Name.LocalName + "[" + (x.ElementsBeforeSelf() .Where(y => y.Name.LocalName == x.Name.LocalName) .Count() + 1) + "]") .ToArray())); } Console.ReadKey(); }
For example, this input:
<foo> <bar> <fizz/> <baz> <bat/> </baz> <fizz/> </bar> <buzz></buzz> </foo>
produces this conclusion:
/foo[1]/bar[1]/fizz[1] /foo[1]/bar[1]/baz[1]/bat[1] /foo[1]/bar[1]/fizz[2] /foo[1]/buzz[1]
source share