Quantcast
Channel: ClearScript
Viewing all articles
Browse latest Browse all 2297

New Post: Host Function that returns dynamic object

$
0
0
Great!

Implementing this method worked.
I will paste it here for future reference:
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;
            var attr = _elements[0].Attribute(XName.Get(binder.Name));
            if (attr != null)
                result = attr.Value;
            else
            {
                var items = _elements.Descendants(XName.Get(binder.Name));
                if (items == null || items.Count() == 0) 
                    return false;
                result = new DynamicXml(items);
            }
            return true;
        }

        public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
        {
            int ndx = (int)indexes[0];
            result = new DynamicXml(_elements[ndx]);
            return true;
        }

        public override IEnumerable<string> GetDynamicMemberNames()
        {
            List<String> memberNames = new List<String>();
            foreach (XAttribute attr in _elements[0].Attributes())
            {
                memberNames.Add(attr.Name.LocalName);
            }
            foreach (XElement child in _elements[0].Descendants())
            {
                memberNames.Add(child.Name.LocalName);
            }
            return memberNames;
        }

        public IEnumerator GetEnumerator()
        {
            foreach (var element in _elements)
                yield return new DynamicXml(element);
        }
    }

Viewing all articles
Browse latest Browse all 2297

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>