PageRenderTime 54ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/Utilities/XmlUtility.cs

https://bitbucket.org/AdamMil/adammil.net
C# | 3078 lines | 2079 code | 342 blank | 657 comment | 525 complexity | 6531c763b1db933cd8d0e9d145109472 MD5 | raw file
Possible License(s): GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. /*
  2. AdamMil.Utilities is a library providing generally useful utilities for
  3. .NET development.
  4. http://www.adammil.net/
  5. Copyright (C) 2010-2016 Adam Milazzo
  6. This program is free software; you can redistribute it and/or
  7. modify it under the terms of the GNU General Public License
  8. as published by the Free Software Foundation; either version 2
  9. of the License, or (at your option) any later version.
  10. This program is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License
  15. along with this program; if not, write to the Free Software
  16. Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  17. */
  18. using System;
  19. using System.Globalization;
  20. using System.Text;
  21. using System.Text.RegularExpressions;
  22. using System.Xml;
  23. namespace AdamMil.Utilities
  24. {
  25. #region XmlDuration
  26. /// <summary>Represents an <c>xs:duration</c> value.</summary>
  27. /// <remarks>An <see cref="XmlDuration"/> works like a <see cref="TimeSpan"/> value, except that it maintains a distinction between the
  28. /// number of years and months in the duration, which may vary in actual length, and the days, hours, minutes, and seconds, which do not.
  29. /// For example, January is longer than February and leap years are longer than regular years, so an <c>xs:duration</c> of <c>P1Y2M</c>
  30. /// (1 year and 2 months) adds a variable amount of real time depending on the date to which it's added. The <see cref="TimeSpan"/>
  31. /// structure does not capture this distinction, and is therefore inappropriate to represent an <c>xs:duration</c> value.
  32. /// <para>The <c>xs:duration</c> format does have some limitations to be aware of, however. An <c>xs:duration</c> can represent a positive
  33. /// or negative span of time, but it cannot represent a span of time where the variable portion is positive and the fixed portion is
  34. /// negative, or vice versa. For instance, you can have a period of one month and one day, or negative one month and negative one day, but
  35. /// you cannot have a period of one month and negative one day or vice versa. This also prevents durations from being added together when
  36. /// the result would not be entirely positive or negative (or zero).
  37. /// </para>
  38. /// <para>The XML Schema specification says "Time durations are added by simply adding each of their fields, respectively, without
  39. /// overflow", where "fields" refers to the components such as month, day, hour, etc. Since adding without overflow is not really
  40. /// possible in a fixed amount of space, and we desire to keep the structure as small as possible without placing tight restrictions on the
  41. /// range of each component, and we want to relax the restrictions on having components with differing signs, adding two
  42. /// <see cref="XmlDuration"/> values will allow overflow between fields. For instance, adding two durations of 40 seconds will yield a
  43. /// duration of 1 minute and 20 seconds rather than a duration of 80 seconds. (The two are equivalent in all ways except for their string
  44. /// representation.) Similarly, adding a duration of -10 seconds to a duration of 1 minute will not be an error but will instead yield a
  45. /// duration of 50 seconds.
  46. /// </para>
  47. /// <para>The <see cref="XmlDuration"/> type is limited to maximums of 2147483647 total months (as any combination of years and months)
  48. /// and approximately 10675199.1167 total days (as any combination of days, hours, minutes, etc). This is not a limitation inherent to the
  49. /// <c>xs:duration</c> format, but one imposed by the fixed amount of space available in the <see cref="XmlDuration"/> structure.
  50. /// </para>
  51. /// </remarks>
  52. [Serializable]
  53. public struct XmlDuration
  54. {
  55. /// <summary>Represents the number of ticks in one millisecond.</summary>
  56. public const long TicksPerMillisecond = 10*1000L; // one tick is 100 nanoseconds, the same as that used by DateTime, Timespan, etc.
  57. /// <summary>Represents the number of ticks in one second.</summary>
  58. public const long TicksPerSecond = TicksPerMillisecond * 1000;
  59. /// <summary>Represents the number of ticks in one minute.</summary>
  60. public const long TicksPerMinute = TicksPerSecond * 60;
  61. /// <summary>Represents the number of ticks in one hour.</summary>
  62. public const long TicksPerHour = TicksPerMinute * 60;
  63. /// <summary>Represents the number of ticks in one day.</summary>
  64. public const long TicksPerDay = TicksPerHour * 24;
  65. /// <summary>Initializes a new <see cref="XmlDuration"/> from the given <see cref="TimeSpan"/> value.</summary>
  66. /// <remarks>All <see cref="TimeSpan"/> values except <see cref="TimeSpan.MinValue"/> can be represented as an <see cref="XmlDuration"/>.</remarks>
  67. /// <exception cref="ArgumentOutOfRangeException">Thrown if <paramref name="timeSpan"/> equals <see cref="TimeSpan.MinValue"/>.</exception>
  68. public XmlDuration(TimeSpan timeSpan)
  69. {
  70. if(timeSpan.Ticks < 0)
  71. {
  72. _ticks = -timeSpan.Ticks; // TODO: it would be nice to remove this limitation
  73. if(_ticks < 0) throw new ArgumentOutOfRangeException("TimeSpan.MinValue cannot be represented as an XmlDuration.");
  74. _months = 0x80000000;
  75. }
  76. else
  77. {
  78. _months = 0;
  79. _ticks = timeSpan.Ticks;
  80. }
  81. }
  82. /// <summary>Initializes a new <see cref="XmlDuration"/> from the given number of years, months, and days.</summary>
  83. /// <include file="documentation.xml" path="/Utilities/XmlDuration/AddSubRemarks/node()"/>
  84. public XmlDuration(int years, int months, int days)
  85. {
  86. if(days < -10675199 || days > 10675199) throw OverflowError();
  87. _ticks = days * TicksPerDay;
  88. _months = GetTotalMonths(years, months);
  89. FixSign();
  90. }
  91. /// <summary>Initializes a new <see cref="XmlDuration"/> from the given components.</summary>
  92. /// <include file="documentation.xml" path="/Utilities/XmlDuration/AddSubRemarks/node()"/>
  93. public XmlDuration(int years, int months, int days, int hours, int minutes, int seconds)
  94. {
  95. if(days < -10675199 || days > 10675199 || hours < -256204778 || hours > 256204778) throw OverflowError();
  96. _ticks = Add(days * TicksPerDay, Add(hours * TicksPerHour, minutes*TicksPerMinute + seconds*TicksPerSecond));
  97. _months = GetTotalMonths(years, months);
  98. FixSign();
  99. }
  100. /// <summary>Initializes a new <see cref="XmlDuration"/> from the given components.</summary>
  101. /// <include file="documentation.xml" path="/Utilities/XmlDuration/AddSubRemarks/node()"/>
  102. public XmlDuration(int years, int months, int days, int hours, int minutes, int seconds, int milliseconds)
  103. {
  104. if(days < -10675199 || days > 10675199 || hours < -256204778 || hours > 256204778) throw OverflowError();
  105. _ticks = Add(days * TicksPerDay,
  106. Add(hours * TicksPerHour, minutes*TicksPerMinute + seconds*TicksPerSecond + milliseconds*TicksPerMillisecond));
  107. _months = GetTotalMonths(years, months);
  108. FixSign();
  109. }
  110. /// <summary>Initializes a new <see cref="XmlDuration"/> from a number of years and months to add, and a number of 100-nanosecond ticks
  111. /// to add.
  112. /// </summary>
  113. /// <include file="documentation.xml" path="/Utilities/XmlDuration/AddSubRemarks/node()"/>
  114. public XmlDuration(int years, int months, long ticks)
  115. {
  116. _ticks = ticks;
  117. _months = GetTotalMonths(years, months);
  118. FixSign();
  119. }
  120. /// <summary>Initializes a new <see cref="XmlDuration"/> from a number months to add or subtract, and a number of 100-nanosecond ticks to
  121. /// add or subtract, and a boolean that indicates whether the duration should be negative (i.e. whether we should subtract instead of
  122. /// add). The numbers of months and ticks must be non-negative.
  123. /// </summary>
  124. /// <exception cref="ArgumentOutOfRangeException">Thrown if <paramref name="totalMonths"/> or <paramref name="ticks"/> is negative.</exception>
  125. public XmlDuration(int totalMonths, long ticks, bool isNegative)
  126. {
  127. if(totalMonths < 0 || ticks < 0) throw new ArgumentOutOfRangeException("An argument was negative.");
  128. if(isNegative && totalMonths == 0 && ticks == 0) isNegative = false;
  129. _ticks = ticks;
  130. _months = (uint)totalMonths | (isNegative ? 0x80000000 : 0u);
  131. }
  132. XmlDuration(uint encodedMonths, long ticks)
  133. {
  134. _ticks = ticks;
  135. _months = encodedMonths;
  136. }
  137. /// <summary>Gets the non-negative days component of this duration value.</summary>
  138. public int Days
  139. {
  140. get { return (int)(_ticks / TicksPerDay); }
  141. }
  142. /// <summary>Gets the non-negative hours component of this duration value.</summary>
  143. public int Hours
  144. {
  145. get { return (int)(_ticks % TicksPerDay / TicksPerHour); }
  146. }
  147. /// <summary>Gets the non-negative milliseconds component of this duration value, excluding the fractional part.</summary>
  148. public int Milliseconds
  149. {
  150. get { return (int)(_ticks % TicksPerSecond) / (int)TicksPerMillisecond; }
  151. }
  152. /// <summary>Gets the non-negative minutes component of this duration value.</summary>
  153. public int Minutes
  154. {
  155. get { return (int)(_ticks % TicksPerHour / TicksPerMinute); }
  156. }
  157. /// <summary>Gets the non-negative months component of this duration value.</summary>
  158. public int Months
  159. {
  160. get { return TotalMonths % 12; }
  161. }
  162. /// <summary>Gets whether the </summary>
  163. public bool IsNegative
  164. {
  165. get { return (int)_months < 0; }
  166. }
  167. /// <summary>Gets the non-negative seconds component of this duration value, including the fractional part.</summary>
  168. public double Seconds
  169. {
  170. get { return (int)(_ticks % TicksPerMinute) / (double)TicksPerSecond; }
  171. }
  172. /// <summary>Gets the non-negative number of ticks encapsulating the day and time components of this duration value.</summary>
  173. public long Ticks
  174. {
  175. get { return _ticks; }
  176. }
  177. /// <summary>Gets the non-negative seconds component of this duration value, excluding the fractional part.</summary>
  178. public int WholeSeconds
  179. {
  180. get { return (int)(_ticks % TicksPerMinute) / (int)TicksPerSecond; }
  181. }
  182. /// <summary>Gets the non-negative years component of this duration value.</summary>
  183. public int Years
  184. {
  185. get { return TotalMonths / 12; }
  186. }
  187. /// <summary>Gets the non-negative total number of months in this duration value.</summary>
  188. public int TotalMonths
  189. {
  190. get { return (int)(_months & 0x7FFFFFFF); }
  191. }
  192. /// <summary>Returns the absolute value of this duration, which will be an <see cref="XmlDuration"/> of the same length but with
  193. /// <see cref="IsNegative"/> equal to false.
  194. /// </summary>
  195. public XmlDuration Abs()
  196. {
  197. return new XmlDuration((uint)TotalMonths, _ticks);
  198. }
  199. /// <summary>Adds the given duration to this duration and returns the result.</summary>
  200. /// <include file="documentation.xml" path="/Utilities/XmlDuration/AddSubRemarks/node()"/>
  201. public XmlDuration Add(XmlDuration duration)
  202. {
  203. if(((uint)(_months ^ duration._months) & 0x80000000) == 0) // if the two durations have the same sign...
  204. {
  205. return new XmlDuration(Add(TotalMonths, duration.TotalMonths), Add(_ticks, duration._ticks), IsNegative);
  206. }
  207. else // if the durations have opposite signs...
  208. {
  209. long ticks = _ticks - duration._ticks;
  210. int months = TotalMonths - duration.TotalMonths;
  211. // if the resulting components have opposite signs, the value cannot be represented as an xs:duration
  212. if(months < 0 ? ticks > 0 : months > 0 && ticks < 0) throw UnrepresentableError();
  213. return months < 0 ? new XmlDuration(-months, -ticks, !IsNegative) : new XmlDuration(months, ticks, IsNegative);
  214. }
  215. }
  216. /// <summary>Adds the given number of days (which can be negative) to this duration and returns the result.</summary>
  217. /// <include file="documentation.xml" path="/Utilities/XmlDuration/AddSubRemarks/node()"/>
  218. public XmlDuration AddDays(double days)
  219. {
  220. return AddTicks((long)(days * TicksPerDay + 0.5));
  221. }
  222. /// <summary>Adds the given number of hours (which can be negative) to this duration and returns the result.</summary>
  223. /// <include file="documentation.xml" path="/Utilities/XmlDuration/AddSubRemarks/node()"/>
  224. public XmlDuration AddHours(double hours)
  225. {
  226. return AddTicks((long)(hours * TicksPerHour + 0.5));
  227. }
  228. /// <summary>Adds the given number of milliseconds (which can be negative) to this duration and returns the result.</summary>
  229. /// <include file="documentation.xml" path="/Utilities/XmlDuration/AddSubRemarks/node()"/>
  230. public XmlDuration AddMilliseconds(double seconds)
  231. {
  232. return AddTicks((long)(seconds * TicksPerMillisecond + 0.5));
  233. }
  234. /// <summary>Adds the given number of minutes (which can be negative) to this duration and returns the result.</summary>
  235. /// <include file="documentation.xml" path="/Utilities/XmlDuration/AddSubRemarks/node()"/>
  236. public XmlDuration AddMinutes(double minutes)
  237. {
  238. return AddTicks((long)(minutes * TicksPerMinute + 0.5));
  239. }
  240. /// <summary>Adds the given number of months (which can be negative) to this duration and returns the result.</summary>
  241. /// <include file="documentation.xml" path="/Utilities/XmlDuration/AddSubRemarks/node()"/>
  242. public XmlDuration AddMonths(int months)
  243. {
  244. if(IsNegative == (months < 0))
  245. {
  246. months = Add(TotalMonths, months);
  247. }
  248. else
  249. {
  250. months = TotalMonths - months;
  251. if(months < 0) throw UnrepresentableError(); // if the result changed sign, it can't be represented as an xs:duration
  252. }
  253. return new XmlDuration(months, _ticks, IsNegative);
  254. }
  255. /// <summary>Adds the given number of seconds (which can be negative) to this duration and returns the result.</summary>
  256. /// <include file="documentation.xml" path="/Utilities/XmlDuration/AddSubRemarks/node()"/>
  257. public XmlDuration AddSeconds(double seconds)
  258. {
  259. return AddTicks((long)(seconds * TicksPerSecond + 0.5));
  260. }
  261. /// <summary>Adds the given number of ticks (which can be negative) to this duration and returns the result.</summary>
  262. /// <include file="documentation.xml" path="/Utilities/XmlDuration/AddSubRemarks/node()"/>
  263. public XmlDuration AddTicks(long ticks)
  264. {
  265. if(IsNegative == (ticks < 0))
  266. {
  267. ticks = Add(_ticks, ticks);
  268. }
  269. else
  270. {
  271. ticks = _ticks - ticks;
  272. if(ticks < 0) throw UnrepresentableError(); // if the result changed sign, it can't be represented as an xs:duration
  273. }
  274. return new XmlDuration(TotalMonths, ticks, IsNegative);
  275. }
  276. /// <summary>Adds the given number of years (which can be negative) to this duration and returns the result.</summary>
  277. /// <include file="documentation.xml" path="/Utilities/XmlDuration/AddSubRemarks/node()"/>
  278. public XmlDuration AddYears(int years)
  279. {
  280. if(years < -178956970 || years > 178956970) throw OverflowError();
  281. return AddMonths(years*12);
  282. }
  283. /// <inheritdoc/>
  284. public override bool Equals(object obj)
  285. {
  286. return obj is XmlDuration && Equals((XmlDuration)obj);
  287. }
  288. /// <summary>Determines whether the given duration equals this one.</summary>
  289. public bool Equals(XmlDuration other)
  290. {
  291. return _ticks == other._ticks && _months == other._months;
  292. }
  293. /// <inheritdoc/>
  294. public override int GetHashCode()
  295. {
  296. return (int)((uint)(ulong)_ticks ^ (uint)((ulong)_ticks >> 32) ^ (uint)_months);
  297. }
  298. /// <summary>Returns an <see cref="XmlDuration"/> with the same length as this one, but the opposite sign.</summary>
  299. public XmlDuration Negate()
  300. {
  301. return new XmlDuration(TotalMonths, _ticks, !IsNegative);
  302. }
  303. /// <summary>Subtractions the given duration from this one and returns the result.</summary>
  304. /// <include file="documentation.xml" path="/Utilities/XmlDuration/AddSubRemarks/node()"/>
  305. public XmlDuration Subtract(XmlDuration duration)
  306. {
  307. return Add(duration.Negate());
  308. }
  309. /// <summary>Returns the duration as an <c>xs:duration</c> value, which is an ISO 8601 duration as extended by the XML Schema
  310. /// specification.
  311. /// </summary>
  312. /// <remarks>For example, <c>P1Y2MT2H</c> represents a duration of one year, two months, and two hours.</remarks>
  313. public override string ToString()
  314. {
  315. StringBuilder sb = new StringBuilder(40);
  316. if(IsNegative) sb.Append('-');
  317. sb.Append('P');
  318. if(TotalMonths != 0)
  319. {
  320. RenderComponent(sb, Years, 'Y');
  321. RenderComponent(sb, Months, 'M');
  322. }
  323. if(_ticks != 0)
  324. {
  325. RenderComponent(sb, Days, 'D');
  326. int hours = Hours, minutes = Minutes, secondTicks = (int)(_ticks % TicksPerMinute);
  327. if((hours|minutes|secondTicks) != 0)
  328. {
  329. sb.Append('T');
  330. RenderComponent(sb, hours, 'H');
  331. RenderComponent(sb, minutes, 'M');
  332. if(secondTicks != 0)
  333. {
  334. int component = secondTicks / (int)TicksPerSecond; // whole seconds
  335. sb.Append(component.ToStringInvariant());
  336. component = secondTicks % (int)TicksPerSecond; // fractional seconds in 100 ns units
  337. if(component != 0) sb.Append('.').Append(component.ToStringInvariant().PadLeft(7, '0').TrimEnd('0'));
  338. sb.Append('S');
  339. }
  340. }
  341. }
  342. if(sb.Length <= 2) sb.Append("0D"); // there has to be at least one component, so add 0 days if we haven't added any components so far
  343. return sb.ToString();
  344. }
  345. /// <summary>Returns a <see cref="TimeSpan"/> that represents the same duration as this <see cref="XmlDuration"/>. Note that not all
  346. /// <see cref="XmlDuration"/> values can be represented as <see cref="TimeSpan"/> values.
  347. /// </summary>
  348. /// <remarks><see cref="TimeSpan"/> values can only represent fixed lengths of time. Month and years are not fixed lengths of time
  349. /// and so durations having non-zero months or years cannot be represented as time spans.
  350. /// </remarks>
  351. /// <exception cref="InvalidOperationException">Thrown if the <see cref="XmlDuration"/> cannot be represented as a
  352. /// <see cref="TimeSpan"/>.
  353. /// </exception>
  354. public TimeSpan ToTimeSpan()
  355. {
  356. if(TotalMonths != 0)
  357. {
  358. throw new InvalidOperationException("This duration cannot be represented by a TimeSpan because it has a variable-length component.");
  359. }
  360. return new TimeSpan(IsNegative ? -Ticks : Ticks);
  361. }
  362. /// <summary>Adds two durations together and returns the result.</summary>
  363. /// <include file="documentation.xml" path="/Utilities/XmlDuration/AddSubRemarks/node()"/>
  364. public static XmlDuration operator+(XmlDuration a, XmlDuration b)
  365. {
  366. return a.Add(b);
  367. }
  368. /// <summary>Subtracts <paramref name="b"/> from <paramref name="a"/> and returns the result.</summary>
  369. /// <include file="documentation.xml" path="/Utilities/XmlDuration/AddSubRemarks/node()"/>
  370. public static XmlDuration operator-(XmlDuration a, XmlDuration b)
  371. {
  372. return a.Add(b.Negate());
  373. }
  374. /// <summary>Negates an <see cref="XmlDuration"/> and returns the result.</summary>
  375. public static XmlDuration operator-(XmlDuration duration)
  376. {
  377. return duration.Negate();
  378. }
  379. /// <summary>Determines if two durations are equal.</summary>
  380. public static bool operator==(XmlDuration a, XmlDuration b)
  381. {
  382. return a._ticks == b._ticks && a._months == b._months;
  383. }
  384. /// <summary>Determines if two durations are unequal.</summary>
  385. public static bool operator!=(XmlDuration a, XmlDuration b)
  386. {
  387. return a._ticks != b._ticks || a._months != b._months;
  388. }
  389. /// <summary>Adds a duration to a <see cref="DateTime"/> and returns the resulting <see cref="DateTime"/>.</summary>
  390. public static DateTime Add(DateTime dateTime, XmlDuration duration)
  391. {
  392. if(duration._months != 0) dateTime = dateTime.AddMonths(duration.IsNegative ? -duration.TotalMonths : (int)duration._months);
  393. if(duration._ticks != 0) dateTime = dateTime.AddTicks(duration.IsNegative ? -duration._ticks : duration._ticks);
  394. return dateTime;
  395. }
  396. /// <summary>Adds a duration to a <see cref="DateTimeOffset"/> and returns the resulting <see cref="DateTimeOffset"/>.</summary>
  397. public static DateTimeOffset Add(DateTimeOffset dateTime, XmlDuration duration)
  398. {
  399. if(duration._months != 0) dateTime = dateTime.AddMonths(duration.IsNegative ? -duration.TotalMonths : (int)duration._months);
  400. if(duration._ticks != 0) dateTime = dateTime.AddTicks(duration.IsNegative ? -duration._ticks : duration._ticks);
  401. return dateTime;
  402. }
  403. /// <summary>Parses an <see cref="XmlDuration"/> from an ISO 8601 duration string as extended by the XML Schema specification.</summary>
  404. /// <remarks>For example, <c>P1Y2MT2H</c> represents a duration of one year, two months, and two hours.</remarks>
  405. public static XmlDuration Parse(string str)
  406. {
  407. if(str == null) throw new ArgumentNullException();
  408. XmlDuration duration;
  409. if(!TryParse(str, out duration)) throw new FormatException();
  410. return duration;
  411. }
  412. /// <summary>Subtracts a duration from a <see cref="DateTime"/> and returns the resulting <see cref="DateTime"/>.</summary>
  413. public static DateTime Subtract(DateTime dateTime, XmlDuration duration)
  414. {
  415. if(duration._months != 0) dateTime = dateTime.AddMonths(duration.IsNegative ? (int)duration._months : -duration.TotalMonths);
  416. if(duration._ticks != 0) dateTime = dateTime.AddTicks(duration.IsNegative ? duration._ticks : -duration._ticks);
  417. return dateTime;
  418. }
  419. /// <summary>Subtracts a duration from a <see cref="DateTimeOffset"/> and returns the resulting <see cref="DateTimeOffset"/>.</summary>
  420. public static DateTimeOffset Subtract(DateTimeOffset dateTime, XmlDuration duration)
  421. {
  422. if(duration._months != 0) dateTime = dateTime.AddMonths(duration.IsNegative ? (int)duration._months : -duration.TotalMonths);
  423. if(duration._ticks != 0) dateTime = dateTime.AddTicks(duration.IsNegative ? duration._ticks : -duration._ticks);
  424. return dateTime;
  425. }
  426. /// <summary>Attempts to parses an <see cref="XmlDuration"/> from an ISO 8601 duration string as extended by the XML Schema
  427. /// specification.
  428. /// </summary>
  429. /// <remarks>For example, <c>P1Y2MT2H</c> represents a duration of one year, two months, and two hours.</remarks>
  430. public static bool TryParse(string str, out XmlDuration duration)
  431. {
  432. if(!string.IsNullOrEmpty(str))
  433. {
  434. Match m = reDuration.Match(str);
  435. if(m.Success)
  436. {
  437. // parse all of the components
  438. int years, months, days, hours, totalMonths;
  439. long mins;
  440. double seconds;
  441. bool hadComponent = false;
  442. if(!ParseGroup(m.Groups["y"], 178956970, ref hadComponent, out years) ||
  443. !ParseGroup(m.Groups["mo"], int.MaxValue, ref hadComponent, out months) ||
  444. !ParseGroup(m.Groups["d"], 10675199, ref hadComponent, out days))
  445. {
  446. goto failed;
  447. }
  448. Group g = m.Groups["h"];
  449. bool hadTimeComponent = g.Success;
  450. if(!ParseGroup(g, 256204778, ref hadComponent, out hours)) goto failed;
  451. g = m.Groups["min"];
  452. hadTimeComponent |= g.Success;
  453. if(!g.Success) mins = 0;
  454. else if(!InvariantCultureUtility.TryParseExact(g.Value, out mins) || mins > 15372286728) goto failed;
  455. else hadComponent = true;
  456. g = m.Groups["s"];
  457. hadTimeComponent |= g.Success;
  458. if(!g.Success)
  459. {
  460. seconds = 0;
  461. }
  462. else if(!double.TryParse(g.Value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out seconds) ||
  463. seconds > 922337203685.47747)
  464. {
  465. goto failed;
  466. }
  467. else
  468. {
  469. hadComponent = true;
  470. }
  471. long longMonths = years*12 + months;
  472. totalMonths = (int)longMonths;
  473. if(totalMonths != longMonths) goto failed; // fail if the total months overflow
  474. long ticks = days * TicksPerDay;
  475. if((ticks += hours*TicksPerHour) < 0 || (ticks += mins*TicksPerMinute) < 0 || (ticks += (long)(seconds*TicksPerSecond + 0.5)) < 0)
  476. {
  477. goto failed; // fail if the ticks overflow
  478. }
  479. // fail if no components were specified (at least one component is required) or if an empty time component was specified
  480. // (which the standard says is illegal)
  481. if(!hadComponent || !hadTimeComponent && m.Groups["time"].Success) goto failed;
  482. duration = new XmlDuration(totalMonths, ticks, m.Groups["n"].Success);
  483. return true;
  484. }
  485. }
  486. failed:
  487. duration = default(XmlDuration);
  488. return false;
  489. }
  490. /// <summary>The largest possible negative <see cref="XmlDuration"/>.</summary>
  491. public static readonly XmlDuration MinValue = new XmlDuration((uint)int.MaxValue | 0x80000000, long.MaxValue);
  492. /// <summary>The largest possible positive <see cref="XmlDuration"/>.</summary>
  493. public static readonly XmlDuration MaxValue = new XmlDuration((uint)int.MaxValue, long.MaxValue);
  494. /// <summary>A zero <see cref="XmlDuration"/>.</summary>
  495. public static readonly XmlDuration Zero = new XmlDuration();
  496. void FixSign()
  497. {
  498. // if the two parts have different signs, the value can't be represented as an xs:duration
  499. if((int)_months < 0 ? _ticks > 0 : (int)_months > 0 && _ticks < 0) throw UnrepresentableError();
  500. // otherwise, if a value was negative and it's not possible to negate both values (because a value is at the minimum)...
  501. if(((int)_months < 0 || _ticks < 0) && ((_months = (uint)-(int)_months ^ 0x80000000) == 0 || (_ticks = -_ticks) < 0))
  502. {
  503. throw OverflowError(); // then it's out of range
  504. }
  505. }
  506. long _ticks;
  507. uint _months;
  508. static int Add(int a, int b)
  509. {
  510. try { return checked(a + b); }
  511. catch(OverflowException) { throw OverflowError(); }
  512. }
  513. static long Add(long a, long b)
  514. {
  515. try { return checked(a + b); }
  516. catch(OverflowException) { throw OverflowError(); }
  517. }
  518. static uint GetTotalMonths(int years, int months)
  519. {
  520. long totalMonths = years*12L + months;
  521. int intValue = (int)totalMonths;
  522. if(totalMonths != intValue || intValue == int.MinValue) throw OverflowError();
  523. return (uint)intValue;
  524. }
  525. static ArgumentOutOfRangeException OverflowError()
  526. {
  527. return new ArgumentOutOfRangeException("The result would be outside the range of XmlDuration.");
  528. }
  529. static bool ParseGroup(Group group, int maxValue, ref bool hadValue, out int value)
  530. {
  531. if(!group.Success) value = 0; // missing components are implicitly equal to zero
  532. else if(!InvariantCultureUtility.TryParseExact(group.Value, out value) || value > maxValue) return false;
  533. else hadValue = true;
  534. return true;
  535. }
  536. static void RenderComponent(StringBuilder sb, int component, char c)
  537. {
  538. if(component != 0) sb.Append(component.ToStringInvariant()).Append(c);
  539. }
  540. static ArgumentException UnrepresentableError()
  541. {
  542. return new ArgumentException("The result is not representable as an xs:duration because the fixed and variable portions of the " +
  543. "duration have opposite signs.");
  544. }
  545. static readonly Regex reDuration =
  546. new Regex(@"^\s*(?<n>-)?P(?:(?<y>[0-9]+)Y)?(?:(?<mo>[0-9]+)M)?(?:(?<d>[0-9]+)D)?(?<time>T(?:(?<h>[0-9]+)H)?(?:(?<min>[0-9]+)M)?(?:(?<s>[0-9]+(?:\.[0-9]+))S)?)?\s*$",
  547. RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Singleline);
  548. }
  549. #endregion
  550. #region XmlDocumentExtensions
  551. /// <summary>Provides useful extensinos to the <see cref="XmlDocument"/> class.</summary>
  552. public static class XmlDocumentExtensions
  553. {
  554. /// <summary>Creates a new <see cref="XmlElement"/> having the given text content.</summary>
  555. public static XmlElement CreateElementWithContent(this XmlDocument document, string qualifiedName, string textValue)
  556. {
  557. XmlElement element = document.CreateElement(qualifiedName);
  558. if(textValue != null) element.AppendChild(document.CreateTextNode(textValue));
  559. return element;
  560. }
  561. }
  562. #endregion
  563. #region XmlElementExtensions
  564. /// <summary>Provides useful extensions to the <see cref="XmlElement"/> class.</summary>
  565. public static class XmlElementExtensions
  566. {
  567. /// <summary>Appends the given <see cref="XmlElement"/> to the end of the list of child nodes, and returns the element.</summary>
  568. public static XmlElement AppendElement(this XmlElement element, XmlElement newChild)
  569. {
  570. if(element == null) throw new ArgumentNullException();
  571. element.AppendChild(newChild);
  572. return newChild;
  573. }
  574. /// <summary>Returns the named attribute value.</summary>
  575. public static string GetAttribute(this XmlElement element, XmlQualifiedName attributeName)
  576. {
  577. if(element == null || attributeName == null) throw new ArgumentNullException();
  578. return element.GetAttribute(attributeName.Name, attributeName.Namespace);
  579. }
  580. /// <summary>Sets the named attribute with a value based on a boolean.</summary>
  581. public static void SetAttribute(this XmlElement element, string attributeName, bool value)
  582. {
  583. if(element == null) throw new ArgumentNullException();
  584. element.SetAttribute(attributeName, XmlConvert.ToString(value));
  585. }
  586. /// <summary>Sets the named attribute with a value based on a byte.</summary>
  587. public static void SetAttribute(this XmlElement element, string attributeName, byte value)
  588. {
  589. if(element == null) throw new ArgumentNullException();
  590. element.SetAttribute(attributeName, XmlConvert.ToString(value));
  591. }
  592. /// <summary>Sets the named attribute with a value based on a character.</summary>
  593. public static void SetAttribute(this XmlElement element, string attributeName, char value)
  594. {
  595. if(element == null) throw new ArgumentNullException();
  596. element.SetAttribute(attributeName, XmlConvert.ToString(value));
  597. }
  598. /// <summary>Sets the named attribute with a value based on a <see cref="DateTime"/>. The <see cref="DateTimeKind"/> of the
  599. /// <see cref="DateTime"/> will be preserved.
  600. /// </summary>
  601. public static void SetAttribute(this XmlElement element, string attributeName, DateTime dateTimeValue)
  602. {
  603. element.SetAttribute(attributeName, dateTimeValue, XmlDateTimeSerializationMode.RoundtripKind);
  604. }
  605. /// <summary>Sets the named attribute with a value based on a <see cref="DateTime"/>.</summary>
  606. public static void SetAttribute(this XmlElement element, string attributeName, DateTime dateTimeValue,
  607. XmlDateTimeSerializationMode dateTimeMode)
  608. {
  609. if(element == null) throw new ArgumentNullException();
  610. element.SetAttribute(attributeName, XmlConvert.ToString(dateTimeValue, dateTimeMode));
  611. }
  612. /// <summary>Sets the named attribute with a value based on a <see cref="Decimal"/>.</summary>
  613. public static void SetAttribute(this XmlElement element, string attributeName, decimal value)
  614. {
  615. if(element == null) throw new ArgumentNullException();
  616. element.SetAttribute(attributeName, XmlConvert.ToString(value));
  617. }
  618. /// <summary>Sets the named attribute with a value based on a 64-bit floating point value.</summary>
  619. public static void SetAttribute(this XmlElement element, string attributeName, double value)
  620. {
  621. if(element == null) throw new ArgumentNullException();
  622. element.SetAttribute(attributeName, XmlConvert.ToString(value));
  623. }
  624. /// <summary>Sets the named attribute with a value based on a <see cref="Guid"/>.</summary>
  625. public static void SetAttribute(this XmlElement element, string attributeName, Guid value)
  626. {
  627. if(element == null) throw new ArgumentNullException();
  628. element.SetAttribute(attributeName, XmlConvert.ToString(value));
  629. }
  630. /// <summary>Sets the named attribute with a value based on a 16-bit integer.</summary>
  631. public static void SetAttribute(this XmlElement element, string attributeName, short value)
  632. {
  633. if(element == null) throw new ArgumentNullException();
  634. element.SetAttribute(attributeName, XmlConvert.ToString(value));
  635. }
  636. /// <summary>Sets the named attribute with a value based on a 32-bit integer.</summary>
  637. public static void SetAttribute(this XmlElement element, string attributeName, int value)
  638. {
  639. if(element == null) throw new ArgumentNullException();
  640. element.SetAttribute(attributeName, XmlConvert.ToString(value));
  641. }
  642. /// <summary>Sets the named attribute with a value based on a 64-bit integer.</summary>
  643. public static void SetAttribute(this XmlElement element, string attributeName, long value)
  644. {
  645. if(element == null) throw new ArgumentNullException();
  646. element.SetAttribute(attributeName, XmlConvert.ToString(value));
  647. }
  648. /// <summary>Sets the named attribute with a value based on an 8-bit integer.</summary>
  649. [CLSCompliant(false)]
  650. public static void SetAttribute(this XmlElement element, string attributeName, sbyte value)
  651. {
  652. if(element == null) throw new ArgumentNullException();
  653. element.SetAttribute(attributeName, XmlConvert.ToString(value));
  654. }
  655. /// <summary>Sets the named attribute with a value based on an 32-bit floating point value.</summary>
  656. public static void SetAttribute(this XmlElement element, string attributeName, float value)
  657. {
  658. if(element == null) throw new ArgumentNullException();
  659. element.SetAttribute(attributeName, XmlConvert.ToString(value));
  660. }
  661. /// <summary>Sets the named attribute with a value based on an <see cref="TimeSpan"/>.</summary>
  662. public static void SetAttribute(this XmlElement element, string attributeName, TimeSpan value)
  663. {
  664. if(element == null) throw new ArgumentNullException();
  665. element.SetAttribute(attributeName, XmlConvert.ToString(value));
  666. }
  667. /// <summary>Sets the named attribute with a value based on a 16-bit unsigned integer.</summary>
  668. [CLSCompliant(false)]
  669. public static void SetAttribute(this XmlElement element, string attributeName, ushort value)
  670. {
  671. if(element == null) throw new ArgumentNullException();
  672. element.SetAttribute(attributeName, XmlConvert.ToString(value));
  673. }
  674. /// <summary>Sets the named attribute with a value based on a 32-bit unsigned integer.</summary>
  675. [CLSCompliant(false)]
  676. public static void SetAttribute(this XmlElement element, string attributeName, uint value)
  677. {
  678. if(element == null) throw new ArgumentNullException();
  679. element.SetAttribute(attributeName, XmlConvert.ToString(value));
  680. }
  681. /// <summary>Sets the named attribute with a value based on a 64-bit unsigned integer.</summary>
  682. [CLSCompliant(false)]
  683. public static void SetAttribute(this XmlElement element, string attributeName, ulong value)
  684. {
  685. if(element == null) throw new ArgumentNullException();
  686. element.SetAttribute(attributeName, XmlConvert.ToString(value));
  687. }
  688. /// <summary>Sets the named attribute with a value based on an <see cref="XmlDuration"/>.</summary>
  689. public static void SetAttribute(this XmlElement element, string attributeName, XmlDuration value)
  690. {
  691. if(element == null) throw new ArgumentNullException();
  692. element.SetAttribute(attributeName, value.ToString());
  693. }
  694. /// <summary>Sets the named attribute.</summary>
  695. public static void SetAttribute(this XmlElement element, XmlQualifiedName attributeName, string value)
  696. {
  697. if(element == null || attributeName == null) throw new ArgumentNullException();
  698. element.SetAttribute(attributeName.Name, attributeName.Namespace, value);
  699. }
  700. /// <summary>Sets the named attribute, using the specified prefix.</summary>
  701. public static void SetAttribute(this XmlElement element, string prefix, string localName, string namespaceUri, string value)
  702. {
  703. if(element == null) throw new ArgumentNullException();
  704. XmlAttribute attr = element.GetAttributeNode(localName, namespaceUri);
  705. if(attr == null || !attr.Prefix.OrdinalEquals(prefix))
  706. {
  707. attr = element.OwnerDocument.CreateAttribute(prefix, localName, namespaceUri);
  708. element.SetAttributeNode(attr);
  709. }
  710. attr.Value = value;
  711. }
  712. /// <summary>Sets the named attribute with a value based on the date portion of a <see cref="DateTime"/>.</summary>
  713. public static void SetDateAttribute(this XmlElement element, string attributeName, DateTime value)
  714. {
  715. if(element == null) throw new ArgumentNullException();
  716. element.SetAttribute(attributeName, value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
  717. }
  718. /// <summary>Sets the named attribute with a value based on the time portion of a <see cref="DateTime"/>. The
  719. /// <see cref="DateTimeKind"/> of the <see cref="DateTime"/> will be preserved.
  720. /// </summary>
  721. public static void SetTimeAttribute(this XmlElement element, string attributeName, DateTime value)
  722. {
  723. element.SetTimeAttribute(attributeName, value, XmlDateTimeSerializationMode.RoundtripKind);
  724. }
  725. /// <summary>Sets the named attribute with a value based on a <see cref="DateTime"/>.</summary>
  726. public static void SetTimeAttribute(this XmlElement element, string attributeName, DateTime value,
  727. XmlDateTimeSerializationMode mode)
  728. {
  729. if(element == null) throw new ArgumentNullException();
  730. element.SetAttribute(attributeName, XmlConvert.ToString(value, mode).Substring(11)); // strip off the date portion
  731. }
  732. }
  733. #endregion
  734. #region XmlNamespaceResolverExtensions
  735. /// <summary>Provides useful extensions to the <see cref="IXmlNamespaceResolver"/> class.</summary>
  736. public static class XmlNamespaceResolverExtensions
  737. {
  738. /// <summary>Parses a qualified name (i.e. a name of the form <c>prefix:localName</c> or <c>namespaceUri:localName</c>) into an
  739. /// <see cref="XmlQualifiedName"/> in the context of the current namespace resolver. This method also accepts local names.
  740. /// </summary>
  741. public static XmlQualifiedName ParseQualifiedName(this IXmlNamespaceResolver resolver, string qualifiedName)
  742. {
  743. if(resolver == null) throw new ArgumentNullException();
  744. return string.IsNullOrEmpty(qualifiedName) ?
  745. XmlQualifiedName.Empty : XmlUtility.ParseQualifiedName(qualifiedName, resolver.LookupNamespace);
  746. }
  747. }
  748. #endregion
  749. #region XmlNodeExtensions
  750. /// <summary>Provides useful extensions to the <see cref="XmlNode"/> class.</summary>
  751. public static class XmlNodeExtensions
  752. {
  753. /// <summary>Returns the value of the named attribute, or <c>default(T)</c> if the attribute was unspecified.</summary>
  754. public static T GetAttribute<T>(this XmlNode node, string attrName, Converter<string, T> converter)
  755. {
  756. return GetAttribute<T>(node, attrName, converter, default(T));
  757. }
  758. /// <summary>Returns the value of the named attribute, or the given default value if the attribute was unspecified.</summary>
  759. public static T GetAttribute<T>(this XmlNode node, string attrName, Converter<string, T> converter,
  760. T defaultValue)
  761. {
  762. if(converter == null) throw new ArgumentNullException("converter");
  763. XmlAttribute an = GetAttributeNode(node, attrName);
  764. return an == null ? defaultValue : converter(an.Value);
  765. }
  766. /// <summary>Returns the value of the named attribute, or null if the attribute was unspecified.</summary>
  767. public static string GetAttributeValue(this XmlNode node, string attrName)
  768. {
  769. return GetAttributeValue(node, attrName, null);
  770. }
  771. /// <summary>Returns the value of the named attribute, or the given default value if the attribute was unspecified.</summary>
  772. public static string GetAttributeValue(this XmlNode node, string attrName, string defaultValue)
  773. {
  774. XmlAttribute an = GetAttributeNode(node, attrName);
  775. return an == null ? defaultValue : an.Value;
  776. }
  777. /// <summary>Returns the value of the named attribute as a boolean, or false if the attribute was unspecified or empty.</summary>
  778. public static bool GetBoolAttribute(this XmlNode node, string attrName)
  779. {
  780. return GetBoolAttribute(node, attrName, false);
  781. }
  782. /// <summary>Returns the value of the named attribute as a boolean, or the given
  783. /// default value if the attribute was unspecified or empty.
  784. /// </summary>
  785. public static bool GetBoolAttribute(this XmlNode node, string attrName, bool defaultValue)
  786. {
  787. string attrValue = GetAttributeValue(node, attrName);
  788. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToBoolean(attrValue);
  789. }
  790. /// <summary>Returns the value of the named attribute as a byte, or 0 if the attribute was unspecified or empty.</summary>
  791. public static byte GetByteAttribute(this XmlNode node, string attrName)
  792. {
  793. return GetByteAttribute(node, attrName, 0);
  794. }
  795. /// <summary>Returns the value of the named attribute as a byte, or the given default
  796. /// value if the attribute was unspecified or empty.
  797. /// </summary>
  798. public static byte GetByteAttribute(this XmlNode node, string attrName, byte defaultValue)
  799. {
  800. string attrValue = GetAttributeValue(node, attrName);
  801. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToByte(attrValue);
  802. }
  803. /// <summary>Returns the value of the named attribute as a character, or the nul character if the attribute was unspecified or empty.</summary>
  804. public static char GetCharAttribute(this XmlNode node, string attrName)
  805. {
  806. return GetCharAttribute(node, attrName, '\0');
  807. }
  808. /// <summary>Returns the value of the named attribute as a character, or the given default
  809. /// value if the attribute was unspecified or empty.
  810. /// </summary>
  811. public static char GetCharAttribute(this XmlNode node, string attrName, char defaultValue)
  812. {
  813. string attrValue = GetAttributeValue(node, attrName);
  814. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToChar(attrValue);
  815. }
  816. /// <summary>Returns the value of the named attribute as a nullable datetime, or null if the attribute was unspecified or empty.</summary>
  817. public static DateTime? GetDateTimeAttribute(this XmlNode node, string attrName)
  818. {
  819. return GetDateTimeAttribute(node, attrName, (DateTime?)null);
  820. }
  821. /// <summary>Returns the value of the named attribute as a nullable datetime, or the given default
  822. /// value if the attribute was unspecified or empty.
  823. /// </summary>
  824. public static DateTime? GetDateTimeAttribute(this XmlNode node, string attrName, DateTime? defaultValue)
  825. {
  826. string attrValue = GetAttributeValue(node, attrName);
  827. return string.IsNullOrEmpty(attrValue) ?
  828. defaultValue : XmlConvert.ToDateTime(attrValue, XmlDateTimeSerializationMode.Unspecified);
  829. }
  830. /// <summary>Returns the value of the named attribute as a decimal, or 0 if the attribute was unspecified or empty.</summary>
  831. public static decimal GetDecimalAttribute(this XmlNode node, string attrName)
  832. {
  833. return GetDecimalAttribute(node, attrName, 0);
  834. }
  835. /// <summary>Returns the value of the named attribute as a decimal, or the given default
  836. /// value if the attribute was unspecified or empty.
  837. /// </summary>
  838. public static decimal GetDecimalAttribute(this XmlNode node, string attrName, decimal defaultValue)
  839. {
  840. string attrValue = GetAttributeValue(node, attrName);
  841. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToDecimal(attrValue);
  842. }
  843. /// <summary>Returns the value of the named attribute as a 64-bit floating point value, or 0 if the attribute was unspecified or empty.</summary>
  844. public static double GetDoubleAttribute(this XmlNode node, string attrName)
  845. {
  846. return GetDoubleAttribute(node, attrName, 0);
  847. }
  848. /// <summary>Returns the value of the named attribute as a 64-bit floating point value, or the given default
  849. /// value if the attribute was unspecified or empty.
  850. /// </summary>
  851. public static double GetDoubleAttribute(this XmlNode node, string attrName, double defaultValue)
  852. {
  853. string attrValue = GetAttributeValue(node, attrName);
  854. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToDouble(attrValue);
  855. }
  856. /// <summary>Returns the value of the named attribute as an <see cref="XmlDuration"/>, or
  857. /// an empty duration if the attribute was unspecified or empty.
  858. /// </summary>
  859. public static XmlDuration GetDurationAttribute(this XmlNode node, string attrName)
  860. {
  861. return GetDurationAttribute(node, attrName, XmlDuration.Zero);
  862. }
  863. /// <summary>Returns the value of the named attribute as a <see cref="XmlDuration"/>, or
  864. /// the given default value if the attribute was unspecified or empty.
  865. /// </summary>
  866. public static XmlDuration GetDurationAttribute(this XmlNode node, string attrName, XmlDuration defaultValue)
  867. {
  868. string attrValue = GetAttributeValue(node, attrName);
  869. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlDuration.Parse(attrValue);
  870. }
  871. /// <summary>Returns the value of the named attribute as a <see cref="Guid"/>, or <see cref="Guid.Empty" />
  872. /// if the attribute was unspecified or empty.
  873. /// </summary>
  874. public static Guid GetGuidAttribute(this XmlNode node, string attrName)
  875. {
  876. return GetGuidAttribute(node, attrName, Guid.Empty);
  877. }
  878. /// <summary>Returns the value of the named attribute as a <see cref="Guid"/>, or the given default
  879. /// value if the attribute was unspecified or empty.
  880. /// </summary>
  881. public static Guid GetGuidAttribute(this XmlNode node, string attrName, Guid defaultValue)
  882. {
  883. string attrValue = GetAttributeValue(node, attrName);
  884. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToGuid(attrValue);
  885. }
  886. /// <summary>Searches the node and its ancestors for the given attribute and returns the first one found, or null if the attribute was
  887. /// not defined on the node or any ancestor.
  888. /// </summary>
  889. public static XmlAttribute GetInheritedAttributeNode(this XmlNode node, string qualifiedName)
  890. {
  891. if(node == null) throw new ArgumentNullException();
  892. while(node.NodeType != XmlNodeType.Document)
  893. {
  894. XmlAttribute attr = node.Attributes[qualifiedName];
  895. if(attr != null) return attr;
  896. node = node.ParentNode;
  897. }
  898. return null;
  899. }
  900. /// <summary>Searches the node and its ancestors for the given attribute and returns the first one found, or null if the attribute was
  901. /// not defined on the node or any ancestor.
  902. /// </summary>
  903. public static XmlAttribute GetInheritedAttributeNode(this XmlNode node, XmlQualifiedName qualifiedName)
  904. {
  905. if(node == null || qualifiedName == null) throw new ArgumentNullException();
  906. while(node.NodeType != XmlNodeType.Document)
  907. {
  908. XmlAttribute attr = node.Attributes[qualifiedName.Name, qualifiedName.Namespace];
  909. if(attr != null) return attr;
  910. node = node.ParentNode;
  911. }
  912. return null;
  913. }
  914. /// <summary>Searches the node and its ancestors for the given attribute and returns the value of the first one found, or null if the
  915. /// attribute was not defined on the node or any ancestor.
  916. /// </summary>
  917. public static string GetInheritedAttributeValue(this XmlNode node, string qualifiedName)
  918. {
  919. return GetInheritedAttributeValue(node, qualifiedName, null);
  920. }
  921. /// <summary>Searches the node and its ancestors for the given attribute and returns the value of the first one found, or the given
  922. /// default value if the attribute was not defined on the node or any ancestor.
  923. /// </summary>
  924. public static string GetInheritedAttributeValue(this XmlNode node, string qualifiedName, string defaultValue)
  925. {
  926. XmlAttribute attr = node.GetInheritedAttributeNode(qualifiedName);
  927. return attr == null ? defaultValue : attr.Value;
  928. }
  929. /// <summary>Searches the node and its ancestors for the given attribute and returns the value of the first one found, or null if the
  930. /// attribute was not defined on the node or any ancestor.
  931. /// </summary>
  932. public static string GetInheritedAttributeValue(this XmlNode node, XmlQualifiedName qualifiedName)
  933. {
  934. return GetInheritedAttributeValue(node, qualifiedName, null);
  935. }
  936. /// <summary>Searches the node and its ancestors for the given attribute and returns the value of the first one found, or the given
  937. /// default value if the attribute was not defined on the node or any ancestor.
  938. /// </summary>
  939. public static string GetInheritedAttributeValue(this XmlNode node, XmlQualifiedName qualifiedName, string defaultValue)
  940. {
  941. XmlAttribute attr = node.GetInheritedAttributeNode(qualifiedName);
  942. return attr == null ? defaultValue : attr.Value;
  943. }
  944. /// <summary>Returns the value of the named attribute as a 16-bit signed integer, or 0 if the attribute was unspecified or empty.</summary>
  945. public static short GetInt16Attribute(this XmlNode node, string attrName)
  946. {
  947. return GetInt16Attribute(node, attrName, 0);
  948. }
  949. /// <summary>Returns the value of the named attribute as a 16-bit signed integer, or the given default
  950. /// value if the attribute was unspecified or empty.
  951. /// </summary>
  952. public static short GetInt16Attribute(this XmlNode node, string attrName, short defaultValue)
  953. {
  954. string attrValue = GetAttributeValue(node, attrName);
  955. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToInt16(attrValue);
  956. }
  957. /// <summary>Returns the value of the named attribute as a 32-bit signed integer, or 0 if the attribute was unspecified or empty.</summary>
  958. public static int GetInt32Attribute(this XmlNode node, string attrName)
  959. {
  960. return GetInt32Attribute(node, attrName, 0);
  961. }
  962. /// <summary>Returns the value of the named attribute as a 32-bit signed in…

Large files files are truncated, but you can click here to view the full file