This is actually a duplicate of this question. While it's not marked as the answer, the method in my answer to that question is the only way of unambiguously formulating the XPath to a node within an XML document that will always work under all circumstances. (It also works for all node types, not just elements.)
As you can see, the XPath it produces is ugly and abstract. but it addresses the concerns that many answerers have raised here. Most of the suggestions made here produce an XPath that, when used to search the original document, will produce a set of one or more nodes that includes the target node. It's that "or more" that's the problem. For instance, if I have an XML representation of a DataSet, the naive XPath to a specific DataRow's element, /DataSet1/DataTable1
, also returns the elements of all of the other DataRows in the DataTable. You can't disambiguate that without knowing something about how the XML is forumlated (like, is there a primary-key element?).
But /node()[1]/node()[4]/node()[11]
, there's only one node that it'll ever return, no matter what.