Search code examples
mustachetemplate-enginenustache

Is it possible with mustache.js to map xml and use xpath routes like {{/root/Customer}}?


Is it possible with mustache.js (or any other template engine) to map xml to template and use xpath routes like?

Hello {{/root/Customer}} 
You have won {{/root/Prise}} 

It is interesting to have possibility to use exactly xpaht queries with filters and axes (what is impossible whith "Json routes").


Solution

  • I have done that trick (for nushache) by implementing IDictionary.

    public class RenderXpath : IDictionary<string,object> 
    {
        XElement xElement;
        public RenderXpath(XElement xElement)
        {
            this.xElement = xElement;
        }
    
        public object this[string key]
        {
            get
            {
                string @value = "";
                var element = xElement.XPathSelectElement(((key as string)??"").Trim());
                if (element.Elements().Count() > 0)
                    return new RenderXpath(element); // support loops
                if (element.Value != null)
                    return element.Value;
                return @value;
            }
            set
            {
                throw new NotImplementedException();
            }
        }
    
        public bool ContainsKey(string key)
        {
            return true;
        }
    
        // all other throws NotImplementedException
        IEnumerator IEnumerable.GetEnumerator()
        {
            throw new NotImplementedException();
        }
    }
    

    The syntax is {{xmlDoc./License/Customer}} Thanks to mustache there is no need to escape '/' char.