XPathNavigatorExt.cs 793 B

12345678910111213141516171819202122
  1. using System;
  2. using System.ComponentModel;
  3. using System.Xml.XPath;
  4. namespace Quadarax.Foundation.Common.Xml.Extensions
  5. {
  6. public static class XPathNavigatorExt
  7. {
  8. public static T GetAttribute<T>(this XPathNavigator oNavigator, string sAttributeName, bool bMandatory, T oDefaultValue)
  9. {
  10. if (string.IsNullOrEmpty(oNavigator.GetAttribute(sAttributeName, "")))
  11. {
  12. if (bMandatory)
  13. throw new Exception(
  14. $"Missing mandatory attribute '{sAttributeName}' in element '{oNavigator.Name}'");
  15. return oDefaultValue;
  16. }
  17. return (T) TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(oNavigator.GetAttribute(sAttributeName, ""));
  18. }
  19. }
  20. }