Advertisement
midspace

XPath converter helper

Apr 29th, 2016
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.54 KB | None | 0 0
  1. XmlDocument xmlDoc = new XmlDocument();
  2. xmlDoc.Load(filename);
  3. XPathNavigator nav = xmlDoc.CreateNavigator();
  4. XPathNavigator navRoot = nav.SelectSingleNode(ElemContext);
  5. string EnvName = GetXMLObject<string>(navRoot, "@" + ElemEnvironmentName);
  6.  
  7. private T GetXMLObject<T>(XPathNavigator navRoot, string name)
  8. {
  9. if (navRoot.SelectSingleNode(name) == null)
  10. {
  11. throw new NotImplementedException(string.Format("The specified property [{0}] does not exist in the xml node. Please re-check your xml.", name));
  12. }
  13.  
  14. object item = navRoot.SelectSingleNode(name).Value;
  15.  
  16. if (typeof(T).Equals(typeof(string)))
  17. {
  18. return (T)item;
  19. }
  20.  
  21. if (typeof(T).Equals(typeof(int)))
  22. {
  23. item = Convert.ToInt32(item);
  24. return (T)item;
  25. }
  26.  
  27. if (typeof(T).Equals(typeof(IntPtr)))
  28. {
  29. // The Convert must be big enough to convert a pointer from a x64 system.
  30. item = new IntPtr(Convert.ToInt64(item));
  31. return (T)item;
  32. }
  33.  
  34. if (typeof(T).Equals(typeof(double)))
  35. {
  36. item = Convert.ToDouble(item);
  37. return (T)item;
  38. }
  39.  
  40. if (typeof(T).Equals(typeof(DateTime)))
  41. {
  42. item = DateTime.Parse((string)item, null);
  43. return (T)item;
  44. }
  45.  
  46. if (typeof(T).Equals(typeof(bool)))
  47. {
  48. item = Convert.ToBoolean(Convert.ToInt32(item));
  49. return (T)item;
  50. }
  51.  
  52. if (typeof(T).Equals(typeof(Guid)))
  53. {
  54. item = new Guid((string)item);
  55. return (T)item;
  56. }
  57.  
  58. if (typeof(T).BaseType.Equals(typeof(Enum)))
  59. {
  60. item = Enum.Parse(typeof(T), (string)item);
  61. return (T)item;
  62. }
  63.  
  64. if (typeof(T).Equals(typeof(CultureInfo)))
  65. {
  66. item = CultureInfo.GetCultureInfoByIetfLanguageTag((string)item);
  67. return (T)item;
  68. }
  69.  
  70. if (typeof(T).Equals(typeof(Rect)))
  71. {
  72. item = new RectConverter().ConvertFromString((string)item);
  73. return (T)item;
  74. }
  75.  
  76. throw new NotImplementedException(string.Format("The datatype [{0}] has not been catered for.", typeof(T).Name));
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement