我的DynamicXML对象遇到了一些问题,它解析XML很棒,而单个元素的效果很好,但是当我有多个子元素时,它就会失败。 我显然缺少一些东西,但我不知道是什么。
这是班级:
public class DynamicXml : DynamicObject
{
readonly XElement element;
public DynamicXml(string xml)
{
element = XElement.Parse(xml);
}
public DynamicXml(XElement xElement)
{
element = xElement;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (element == null)
{
result = null;
return false;
}
var sub = element.Element(binder.Name);
if (sub == null)
{
result = null;
return false;
}
else
{
result = new DynamicXml(sub);
return true;
}
}
public override string ToString()
{
return element != null ? element.Value : string.Empty;
}
public override bool TryConvert(ConvertBinder binder, out object result)
{
try
{
result = Convert.ChangeType(element.Value, binder.ReturnType);
return true;
}
catch { }
return base.TryConvert(binder, out result);
}
}
这就是我使用它的方式
var response = "<response><foo>some xml here</foo></response>"
result = new DynamicXml(response);
var newObj = new SumObject();
newObj.Foo = result.foo;
现在这个工作正常,但如果我的xml是:
<response>
<foo>
<bahs>
<bah>value here</bah>
<bah>value here</bah>
<bah>value here</bah>
</bahs>
</foo>
<response>
我想用一些东西:
for(var bahs in result.foo.bahs)
{
//magic code here
}
但这不是发生的事情我只是得到一个错误:
Cannot implicitly convert type 'DynamicXml' to 'System.Collections.IEnumerable'. An explicit conversion exists (are you missing a cast?)
非常感谢您的帮助。
答案 0 :(得分:3)
我想出了解决方案,我需要实现IEnumerable和GetEnumerator()
这是解决方案类:
public class DynamicXml : DynamicObject, IEnumerable
{
readonly XElement element;
public DynamicXml(string xml)
{
element = XElement.Parse(xml);
}
public DynamicXml(XElement xElement)
{
element = xElement;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (element == null)
{
result = null;
return false;
}
var sub = element.Element(binder.Name);
if (sub == null)
{
result = null;
return false;
}
else
{
result = new DynamicXml(sub);
return true;
}
}
public override string ToString()
{
return element != null ? element.Value : string.Empty;
}
public IEnumerator GetEnumerator()
{
return element.Elements().Select(child => new DynamicXml(child)).GetEnumerator();
}
public override bool TryConvert(ConvertBinder binder, out object result)
{
try
{
result = Convert.ChangeType(element.Value, binder.ReturnType);
return true;
}
catch { }
return base.TryConvert(binder, out result);
}
}