Using an XPath-style Query with Reflection

2020-07-13 07:50发布

问题:

I have a class tree, which contains multiple objects in a hierarchy. So I might have a Container object, which hosts 3 SubContainer objects, which in turn host an arbitrary number of Item objects.

Is there any way that I can use an XPath-style expression over this object tree, which would imply reflection, so that I could query a property of a class with an XPath-style expression, so that the code would look something like:

object o = Container.Query("/Container/SubContainer[1]/Item[1]/@ItemProperty");

Obviously that's completely made up and probably isn't valid XPath syntax, but it's just illustratory to give you an idea of what it is I'm looking for.

Edit -> The reason I would like to query in this manner is because the path to the object is not fixed, and therefore needs to be configurable by the application user.

Thanks.

回答1:

I had the same kind of problem, so wrote a simple kind of extension to query objects using reflection

http://code.google.com/p/antix-software/wiki/AntixReflectionQuery

If it doesn't do exactly what you need, it will at least be a start



回答2:

You can write an extension method to Control that takes a string as you describe.

You will have to write the parser for it and use that to do the actual querying.