XmlReaderExt.cs 1.0 KB

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