0

For example:

public static string GetXPath<TModel, TMember>(this TModel model, Expression<Func<TModel, TMember>> expr)
{
   ...
}

var result = new MyObject().GetXPath(x=> x.DataList[1].Value);

Console.WriteLine(result); 

And this will print out something like this (structure without attributes, just like DataContractSerializer do by default):

/DataList[1]/Value
eocron
  • 6,885
  • 1
  • 21
  • 50
  • 1
    That's not "retrieving" the XPath, you want an `Expression`-to-XPath compiler. Which is certainly an interesting thing to build, but not a simple one. – Jeroen Mostert Sep 04 '17 at 11:17
  • Note that even LINQ to XML doesn't attempt such a thing: instead there's a [page on how to write with LINQ to XML to do what you normally do with XQuery](https://learn.microsoft.com/dotnet/csharp/programming-guide/concepts/linq/linq-to-xml-for-xpath-users). There's no "LINQ to XQuery". Such a thing would have limited value; you'd use it if your data provider only stored XML and processed only XQuery, as opposed to, say, almost anything else that's faster and easier. The best I could find are a few abandoned hobby projects. – Jeroen Mostert Sep 04 '17 at 11:38
  • Well, yes, it will limit value, but there is indeed some benefits from it - it is serializable, and basically serves as some kind of "pointer" in XML. Actually it is query, but if I restrict it by removing unnecessary sugar - it will become serializable pointer to property, like in example above. – eocron Sep 04 '17 at 12:02
  • [Serializing expression trees is a topic all of its own](https://stackoverflow.com/q/217961). If your source format is XML, then yes, using XPath as a serialization format for member expressions makes some sense. Do you have a specific question on how to write the code for it? It just comes down to something that visits expression trees and translates to XPath. There's nothing like that already in the framework, so it's not going to be a oneliner. You can make it as simple or as complicated as you like (XPath is pretty rich). – Jeroen Mostert Sep 04 '17 at 12:11

0 Answers0