Personally, I agree with the other answers that a LINQ to XML based solution is best. Something like:
string xml = "<root><foo><bar>baz</bar></foo></root>";
string s = XElement.Parse(xml).Element("foo").Element("bar").Value;
But if you really wanted behaviour like your example, you could write a small wrapper class such as:
EDIT: Example updated to be indexable using a multidimensional indexernote.
class MyXmlWrapper
{
XElement _xml;
public MyXmlWrapper(XElement xml)
{
_xml = xml;
}
public MyXmlWrapper this[string name, int index = 0]
{
get
{
return new MyXmlWrapper(_xml.Elements(name).ElementAt(index));
}
}
public static implicit operator string(MyXmlWrapper xml)
{
return xml._xml.Value;
}
}
And use that exactly like you wanted:
string xml = "<root><foo><bar>baz</bar></foo></root>";
MyXmlWrapper wrapper = new MyXmlWrapper(XElement.Parse(xml));
string s = wrapper["foo"]["bar"];
Edited example for returning an element from a collection:
string xml = "<root><foo><bar><baz>1</baz><baz>2</baz></bar></foo></root>";
MyXmlWrapper wrapper = new MyXmlWrapper(XElement.Parse(xml));
string baz1 = wrapper["foo"]["bar"]["baz", 0];
string baz2 = wrapper["foo"]["bar"]["baz", 1];