class Program
{
static void Main(string[] args)
{
string xml = @"<root>
<books>
<book>
<author>TOM</author>
<title>E.G.Tttle</title>
<price>20.5</price>
</book>
<book>
<author>JERRY</author>
<title>E.G.Tttle</title>
<price>10.2</price>
</book>
</books>
</root>";
dynamic dx = new DynamicXml(xml);
foreach (dynamic b in dx.books.book)
{
Console.WriteLine("author='{0}'",b.author.Value);
}
Console.ReadLine();
}
}
public class DynamicXml : DynamicObject, IEnumerable
{
private readonly List<XElement> _elements;
public DynamicXml(string text)
{
var doc = XDocument.Parse(text);
_elements = new List<XElement> { doc.Root };
}
protected DynamicXml(XElement element)
{
_elements = new List<XElement> { element };
}
protected DynamicXml(IEnumerable<XElement> elements)
{
_elements = new List<XElement>(elements);
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = null;
if (binder.Name == "Value")
result = _elements[0].Value;
else if (binder.Name == "Count")
result = _elements.Count;
else
{
var attr = _elements[0].Attribute
(
XName.Get(binder.Name)
);
if (attr != null)
{
result = attr;
}
else
{
var items = _elements.Descendants(
XName.Get(binder.Name)
);
if (items == null || items.Count() == 0)
return false;
result = new DynamicXml(items);
}
}
return true;
}
public IEnumerator GetEnumerator()
{
foreach (var element in _elements)
{
yield return new DynamicXml(element);
}
}
}
网上 的一段动态类型的实例。。请问高手为什么foreach (dynamic b in dx.books.book)能对dx.books.book进行循环操作。。??不是只能对dx嘛??请高手解释下这段代码!!!!!!