using System;
using System.ComponentModel;
using System.Xml.XPath;

namespace Quadarax.Foundation.Common.Xml.Extensions
{
    public static class XPathNavigatorExt
    {
        public static T GetAttribute<T>(this XPathNavigator oNavigator, string sAttributeName, bool bMandatory, T oDefaultValue)
        {
            if (string.IsNullOrEmpty(oNavigator.GetAttribute(sAttributeName, "")))
            {
                if (bMandatory)
                    throw new Exception(
                        $"Missing mandatory attribute '{sAttributeName}' in element '{oNavigator.Name}'");
                return oDefaultValue;
            }
            return (T) TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(oNavigator.GetAttribute(sAttributeName, ""));
        }
       
    }
}
