XmlNodeExt.cs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. using System;
  2. using System.ComponentModel;
  3. using System.Xml;
  4. namespace Quadarax.Foundation.Common.Extensions
  5. {
  6. public static class XmlNodeExt
  7. {
  8. public static T GetAttribute<T>(this XmlNode node, string sAttributeName, bool bMandatory, T oDefaultValue)
  9. {
  10. if (string.IsNullOrEmpty(node.GetAttribute(sAttributeName)))
  11. {
  12. if (bMandatory)
  13. throw new Exception(
  14. $"Missing mandatory attribute '{sAttributeName}' in element '{node.Name}'");
  15. return oDefaultValue;
  16. }
  17. return (T) TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(node.GetAttribute(sAttributeName));
  18. }
  19. public static string GetAttribute(this XmlNode node, string attributeName)
  20. {
  21. if (node?.Attributes == null)
  22. return string.Empty;
  23. foreach (XmlAttribute attr in node.Attributes)
  24. {
  25. if (attr.Name == attributeName)
  26. return attr.Value;
  27. }
  28. return string.Empty;
  29. }
  30. }
  31. }