PageRenderTime 40ms CodeModel.GetById 17ms 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
  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 integer, or the given default
  963. /// value if the attribute was unspecified or empty.
  964. /// </summary>
  965. public static int GetInt32Attribute(this XmlNode node, string attrName, int defaultValue)
  966. {
  967. string attrValue = GetAttributeValue(node, attrName);
  968. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToInt32(attrValue);
  969. }
  970. /// <summary>Returns the value of the named attribute as a 64-bit signed integer, or 0 if the attribute was unspecified or empty.</summary>
  971. public static long GetInt64Attribute(this XmlNode node, string attrName)
  972. {
  973. return GetInt64Attribute(node, attrName, 0);
  974. }
  975. /// <summary>Returns the value of the named attribute as a 64-bit signed integer, or the given default
  976. /// value if the attribute was unspecified or empty.
  977. /// </summary>
  978. public static long GetInt64Attribute(this XmlNode node, string attrName, long defaultValue)
  979. {
  980. string attrValue = GetAttributeValue(node, attrName);
  981. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToInt64(attrValue);
  982. }
  983. /// <summary>Returns the value of the named attribute, or null if the attribute was unspecified.</summary>
  984. public static string GetQualifiedAttributeValue(this XmlNode node, string localName, string namespaceUri)
  985. {
  986. XmlAttribute an = GetAttributeNode(node, localName, namespaceUri);
  987. return an == null ? null : an.Value;
  988. }
  989. /// <summary>Returns the value of the named attribute, or the given default value if the attribute was unspecified.</summary>
  990. public static string GetQualifiedAttributeValue(this XmlNode node, string localName, string namespaceUri, string defaultValue)
  991. {
  992. XmlAttribute an = GetAttributeNode(node, localName, namespaceUri);
  993. return an == null ? defaultValue : an.Value;
  994. }
  995. /// <summary>Returns the value of the named attribute as an 8-bit signed integer, or 0 if the attribute was unspecified or empty.</summary>
  996. [CLSCompliant(false)]
  997. public static sbyte GetSByteAttribute(this XmlNode node, string attrName)
  998. {
  999. return GetSByteAttribute(node, attrName, 0);
  1000. }
  1001. /// <summary>Returns the value of the named attribute as an 8-bit signed integer, or the given default
  1002. /// value if the attribute was unspecified or empty.
  1003. /// </summary>
  1004. [CLSCompliant(false)]
  1005. public static sbyte GetSByteAttribute(this XmlNode node, string attrName, sbyte defaultValue)
  1006. {
  1007. string attrValue = GetAttributeValue(node, attrName);
  1008. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToSByte(attrValue);
  1009. }
  1010. /// <summary>Returns the value of the named attribute as a 32-bit floating point value, or 0 if the attribute was unspecified or empty.</summary>
  1011. public static float GetSingleAttribute(this XmlNode node, string attrName)
  1012. {
  1013. return GetSingleAttribute(node, attrName, 0);
  1014. }
  1015. /// <summary>Returns the value of the named attribute as a 32-bit floating point value, or the given default
  1016. /// value if the attribute was unspecified or empty.
  1017. /// </summary>
  1018. public static float GetSingleAttribute(this XmlNode node, string attrName, float defaultValue)
  1019. {
  1020. string attrValue = GetAttributeValue(node, attrName);
  1021. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToSingle(attrValue);
  1022. }
  1023. /// <summary>Returns the value of the named attribute as a string, or the empty string if the attribute was unspecified or empty.</summary>
  1024. public static string GetStringAttribute(this XmlNode node, string attrName)
  1025. {
  1026. return GetStringAttribute(node, attrName, string.Empty);
  1027. }
  1028. /// <summary>Returns the value of the named attribute as a string, or the given default
  1029. /// value if the attribute was unspecified or empty.
  1030. /// </summary>
  1031. public static string GetStringAttribute(this XmlNode node, string attrName, string defaultValue)
  1032. {
  1033. string attrValue = GetAttributeValue(node, attrName);
  1034. return string.IsNullOrEmpty(attrValue) ? defaultValue : attrValue;
  1035. }
  1036. /// <summary>Returns the value of the named attribute as a <see cref="TimeSpan"/>, or
  1037. /// an empty timespan if the attribute was unspecified or empty.
  1038. /// </summary>
  1039. public static TimeSpan GetTimeSpanAttribute(this XmlNode node, string attrName)
  1040. {
  1041. return GetTimeSpanAttribute(node, attrName, new TimeSpan());
  1042. }
  1043. /// <summary>Returns the value of the named attribute as a <see cref="TimeSpan"/>, or
  1044. /// the given default value if the attribute was unspecified or empty.
  1045. /// </summary>
  1046. public static TimeSpan GetTimeSpanAttribute(this XmlNode node, string attrName, TimeSpan defaultValue)
  1047. {
  1048. string attrValue = GetAttributeValue(node, attrName);
  1049. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToTimeSpan(attrValue);
  1050. }
  1051. /// <summary>Returns the value of the named attribute as a 16-bit unsigned integer, or 0 if the attribute was unspecified or empty.</summary>
  1052. [CLSCompliant(false)]
  1053. public static ushort GetUInt16Attribute(this XmlNode node, string attrName)
  1054. {
  1055. return GetUInt16Attribute(node, attrName, 0);
  1056. }
  1057. /// <summary>Returns the value of the named attribute as a 16-bit unsigned integer, or the given default
  1058. /// value if the attribute was unspecified or empty.
  1059. /// </summary>
  1060. [CLSCompliant(false)]
  1061. public static ushort GetUInt16Attribute(this XmlNode node, string attrName, ushort defaultValue)
  1062. {
  1063. string attrValue = GetAttributeValue(node, attrName);
  1064. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToUInt16(attrValue);
  1065. }
  1066. /// <summary>Returns the value of the named attribute as a 32-bit unsigned integer, or 0 if the attribute was unspecified or empty.</summary>
  1067. [CLSCompliant(false)]
  1068. public static uint GetUInt32Attribute(this XmlNode node, string attrName)
  1069. {
  1070. return GetUInt32Attribute(node, attrName, 0);
  1071. }
  1072. /// <summary>Returns the value of the named attribute as a 32-bit unsigned integer, or the given default
  1073. /// value if the attribute was unspecified or empty.
  1074. /// </summary>
  1075. [CLSCompliant(false)]
  1076. public static uint GetUInt32Attribute(this XmlNode node, string attrName, uint defaultValue)
  1077. {
  1078. string attrValue = GetAttributeValue(node, attrName);
  1079. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToUInt32(attrValue);
  1080. }
  1081. /// <summary>Returns the value of the named attribute as a 64-bit unsigned integer, or 0 if the attribute was unspecified or empty.</summary>
  1082. [CLSCompliant(false)]
  1083. public static ulong GetUInt64Attribute(this XmlNode node, string attrName)
  1084. {
  1085. return GetUInt64Attribute(node, attrName, 0);
  1086. }
  1087. /// <summary>Returns the value of the named attribute as a 64-bit unsigned integer, or the given default
  1088. /// value if the attribute was unspecified or empty.
  1089. /// </summary>
  1090. [CLSCompliant(false)]
  1091. public static ulong GetUInt64Attribute(this XmlNode node, string attrName, ulong defaultValue)
  1092. {
  1093. string attrValue = GetAttributeValue(node, attrName);
  1094. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToUInt64(attrValue);
  1095. }
  1096. /// <summary>Returns the first child node of type <see cref="XmlNodeType.Element"/>, or null if there is no such child node.</summary>
  1097. public static XmlElement GetFirstChildElement(this XmlNode node)
  1098. {
  1099. if(node == null) throw new ArgumentNullException();
  1100. XmlNode child = node.FirstChild;
  1101. while(child != null && child.NodeType != XmlNodeType.Element) child = child.NextSibling;
  1102. return (XmlElement)child;
  1103. }
  1104. /// <summary>Returns the next sibling node of type <see cref="XmlNodeType.Element"/>, or null if there is no such node.</summary>
  1105. public static XmlElement GetNextSiblingElement(this XmlNode node)
  1106. {
  1107. if(node == null) throw new ArgumentNullException();
  1108. do node = node.NextSibling; while(node != null && node.NodeType != XmlNodeType.Element);
  1109. return (XmlElement)node;
  1110. }
  1111. /// <summary>Returns the previous sibling node of type <see cref="XmlNodeType.Element"/>, or null if there is no such node.</summary>
  1112. public static XmlElement GetPreviousSiblingElement(this XmlNode node)
  1113. {
  1114. if(node == null) throw new ArgumentNullException();
  1115. do node = node.PreviousSibling; while(node != null && node.NodeType != XmlNodeType.Element);
  1116. return (XmlElement)node;
  1117. }
  1118. /// <summary>Returns the trimmed value of the node's inner text, or the given default value if the value is empty.</summary>
  1119. public static string GetTrimmedInnerText(this XmlNode node, string defaultValue)
  1120. {
  1121. string innerText = node.InnerText.Trim();
  1122. return string.IsNullOrEmpty(innerText) ? defaultValue : innerText;
  1123. }
  1124. /// <summary>Returns the <see cref="XmlQualifiedName"/> for the node.</summary>
  1125. public static XmlQualifiedName GetQualifiedName(this XmlNode node)
  1126. {
  1127. if(node == null) throw new ArgumentNullException();
  1128. return new XmlQualifiedName(node.LocalName, node.NamespaceURI);
  1129. }
  1130. /// <summary>Returns true if the node contains any non-text children.</summary>
  1131. public static bool HasComplexContent(this XmlNode node)
  1132. {
  1133. if(node == null) throw new ArgumentNullException();
  1134. for(XmlNode child = node.FirstChild; child != null; child = child.NextSibling)
  1135. {
  1136. if(!child.IsTextNode()) return true;
  1137. }
  1138. return false;
  1139. }
  1140. /// <summary>Determines whether the qualified name of the node equals the given qualified name.</summary>
  1141. public static bool HasName(this XmlNode node, XmlQualifiedName qname)
  1142. {
  1143. if(node == null || qname == null) throw new ArgumentNullException();
  1144. return node.HasName(qname.Name, qname.Namespace);
  1145. }
  1146. /// <summary>Determines whether the qualified name of the node equals the given qualified name.</summary>
  1147. public static bool HasName(this XmlNode node, string localName, string namespaceUri)
  1148. {
  1149. if(node == null) throw new ArgumentNullException();
  1150. if(string.IsNullOrEmpty(localName) || namespaceUri == null)
  1151. {
  1152. throw new ArgumentException("Local name must not be empty and namespace URI must not be null.");
  1153. }
  1154. return localName.OrdinalEquals(node.LocalName) && namespaceUri.OrdinalEquals(node.NamespaceURI);
  1155. }
  1156. /// <summary>Returns true if the node contains text children and only text children. (This includes CDATA and whitespace.)
  1157. /// This method returns false for empty elements. Although intended to be called on elements, this method also works for
  1158. /// attributes, in which case it will return true if the attribute value is not empty.
  1159. /// </summary>
  1160. public static bool HasSimpleContent(this XmlNode node)
  1161. {
  1162. if(node == null) throw new ArgumentNullException();
  1163. bool hasText = false;
  1164. for(XmlNode child = node.FirstChild; child != null; child = child.NextSibling)
  1165. {
  1166. if(child.IsTextNode()) hasText = true;
  1167. else return false;
  1168. }
  1169. return hasText || node.NodeType == XmlNodeType.Attribute && !string.IsNullOrEmpty(node.Value);
  1170. }
  1171. /// <summary>Returns true if the node contains text children and only text children - this includes CDATA and whitespace - and at
  1172. /// least one of the children contains characters besides whitespace. This method returns false for empty elements. Although intended
  1173. /// to be called on elements, this method also works for attributes, in which case it will return true if the attribute value is not
  1174. /// empty or whitespace.
  1175. /// </summary>
  1176. public static bool HasSimpleNonSpaceContent(this XmlNode node)
  1177. {
  1178. if(node == null) throw new ArgumentNullException();
  1179. bool hasText = false;
  1180. for(XmlNode child = node.FirstChild; child != null; child = child.NextSibling)
  1181. {
  1182. if(!child.IsTextNode()) return false;
  1183. else if(!StringUtility.IsNullOrSpace(child.Value)) hasText = true;
  1184. }
  1185. return hasText || node.NodeType == XmlNodeType.Attribute && !StringUtility.IsNullOrSpace(node.Value);
  1186. }
  1187. /// <summary>Returns true if the attribute was unspecified or empty.</summary>
  1188. public static bool IsAttributeEmpty(XmlAttribute attr)
  1189. {
  1190. return attr == null || string.IsNullOrEmpty(attr.Value);
  1191. }
  1192. /// <summary>Returns true if the attribute was unspecified or empty.</summary>
  1193. public static bool IsAttributeEmpty(this XmlNode node, string attrName)
  1194. {
  1195. return IsAttributeEmpty(GetAttributeNode(node, attrName));
  1196. }
  1197. /// <summary>Returns true if the node represents some type of text content. (This returns true for <see cref="XmlNodeType.Text"/>,
  1198. /// <see cref="XmlNodeType.Whitespace"/>, <see cref="XmlNodeType.SignificantWhitespace"/>, and <see cref="XmlNodeType.CDATA"/>.)
  1199. /// </summary>
  1200. public static bool IsTextNode(this XmlNode node)
  1201. {
  1202. if(node == null) throw new ArgumentNullException();
  1203. XmlNodeType type = node.NodeType;
  1204. return type == XmlNodeType.Text || type == XmlNodeType.CDATA || type == XmlNodeType.SignificantWhitespace ||
  1205. type == XmlNodeType.Whitespace;
  1206. }
  1207. /// <summary>Parses an attribute whose value contains a whitespace-separated list of items into an array of strings containing
  1208. /// the substrings corresponding to the individual items.
  1209. /// </summary>
  1210. public static string[] ParseListAttribute(this XmlNode node, string attrName)
  1211. {
  1212. return XmlUtility.ParseList(GetAttributeValue(node, attrName));
  1213. }
  1214. /// <summary>Parses an attribute whose value contains a whitespace-separated list of items into an array containing the
  1215. /// corresponding items, using the given converter to convert an item's string representation into its value.
  1216. /// </summary>
  1217. public static T[] ParseListAttribute<T>(this XmlNode node, string attrName, Converter<string, T> converter)
  1218. {
  1219. return XmlUtility.ParseList(GetAttributeValue(node, attrName), converter);
  1220. }
  1221. /// <summary>Parses a qualified name (i.e. a name of the form <c>prefix:localName</c> or <c>namespaceUri:localName</c>) into an
  1222. /// <see cref="XmlQualifiedName"/> in the context of the current node. This method also accepts local names.
  1223. /// </summary>
  1224. public static XmlQualifiedName ParseQualifiedName(this XmlNode node, string qualifiedName)
  1225. {
  1226. if(node == null) throw new ArgumentNullException();
  1227. return string.IsNullOrEmpty(qualifiedName) ?
  1228. XmlQualifiedName.Empty : XmlUtility.ParseQualifiedName(qualifiedName, node.GetNamespaceOfPrefix);
  1229. }
  1230. /// <summary>Removes all the child nodes of the given node.</summary>
  1231. public static void RemoveChildren(this XmlNode node)
  1232. {
  1233. if(node == null) throw new ArgumentNullException();
  1234. while(node.FirstChild != null) node.RemoveChild(node.FirstChild);
  1235. }
  1236. /// <summary>Removes the node from its parent and therefore from the document.</summary>
  1237. public static void RemoveFromParent(this XmlNode node)
  1238. {
  1239. if(node == null) throw new ArgumentNullException();
  1240. if(node.ParentNode != null) node.ParentNode.RemoveChild(node);
  1241. }
  1242. /// <summary>Returns the inner text of the node selected by the given XPath query as a boolean,
  1243. /// or false if the node could not be found or was empty.
  1244. /// </summary>
  1245. public static bool SelectBool(this XmlNode node, string xpath)
  1246. {
  1247. return SelectBool(node, xpath, false);
  1248. }
  1249. /// <summary>Returns the inner text of the node selected by the given XPath query as a boolean,
  1250. /// or the given default value if the node could not be found or was empty.
  1251. /// </summary>
  1252. public static bool SelectBool(this XmlNode node, string xpath, bool defaultValue)
  1253. {
  1254. string stringValue = SelectValue(node, xpath);
  1255. return string.IsNullOrEmpty(stringValue) ? defaultValue : XmlConvert.ToBoolean(stringValue);
  1256. }
  1257. /// <summary>Returns the inner text of the node selected by the given XPath query as a byte,
  1258. /// or 0 if the node could not be found or was empty.
  1259. /// </summary>
  1260. public static byte SelectByte(this XmlNode node, string xpath)
  1261. {
  1262. return SelectByte(node, xpath, 0);
  1263. }
  1264. /// <summary>Returns the inner text of the node selected by the given XPath query as a byte,
  1265. /// or the given default value if the node could not be found or was empty.
  1266. /// </summary>
  1267. public static byte SelectByte(this XmlNode node, string xpath, byte defaultValue)
  1268. {
  1269. string stringValue = SelectValue(node, xpath);
  1270. return string.IsNullOrEmpty(stringValue) ? defaultValue : XmlConvert.ToByte(stringValue);
  1271. }
  1272. /// <summary>Returns the inner text of the node selected by the given XPath query as a character,
  1273. /// or the nul character if the node could not be found or was empty.
  1274. /// </summary>
  1275. public static char SelectChar(this XmlNode node, string xpath)
  1276. {
  1277. return SelectChar(node, xpath, '\0');
  1278. }
  1279. /// <summary>Returns the inner text of the node selected by the given XPath query as a character,
  1280. /// or the given default value if the node could not be found or was empty.
  1281. /// </summary>
  1282. public static char SelectChar(this XmlNode node, string xpath, char defaultValue)
  1283. {
  1284. string stringValue = SelectValue(node, xpath);
  1285. return string.IsNullOrEmpty(stringValue) ? defaultValue : XmlConvert.ToChar(stringValue);
  1286. }
  1287. /// <summary>Returns the inner text of the node selected by the given XPath query as a nullable <see cref="DateTime"/>,
  1288. /// or null if the node could not be found or was empty.
  1289. /// </summary>
  1290. public static DateTime? SelectDateTime(this XmlNode node, string xpath)
  1291. {
  1292. return SelectDateTime(node, xpath, null);
  1293. }
  1294. /// <summary>Returns the inner text of the node selected by the given XPath query as a nullable <see cref="DateTime"/>,
  1295. /// or the given default value if the node could not be found or was empty.
  1296. /// </summary>
  1297. public static DateTime? SelectDateTime(this XmlNode node, string xpath, DateTime? defaultValue)
  1298. {
  1299. string stringValue = SelectValue(node, xpath);
  1300. return string.IsNullOrEmpty(stringValue) ?
  1301. defaultValue : XmlConvert.ToDateTime(stringValue, XmlDateTimeSerializationMode.Unspecified);
  1302. }
  1303. /// <summary>Returns the inner text of the node selected by the given XPath query as a decimal,
  1304. /// or 0 if the node could not be found or was empty.
  1305. /// </summary>
  1306. public static decimal SelectDecimal(this XmlNode node, string xpath)
  1307. {
  1308. return SelectDecimal(node, xpath, 0);
  1309. }
  1310. /// <summary>Returns the inner text of the node selected by the given XPath query as a decimal,
  1311. /// or the given default value if the node could not be found or was empty.
  1312. /// </summary>
  1313. public static decimal SelectDecimal(this XmlNode node, string xpath, decimal defaultValue)
  1314. {
  1315. string stringValue = SelectValue(node, xpath);
  1316. return string.IsNullOrEmpty(stringValue) ? defaultValue : XmlConvert.ToDecimal(stringValue);
  1317. }
  1318. /// <summary>Returns the inner text of the node selected by the given XPath query as a 64-bit floating point value,
  1319. /// or 0 if the node could not be found or was empty.
  1320. /// </summary>
  1321. public static double SelectDouble(this XmlNode node, string xpath)
  1322. {
  1323. return SelectDouble(node, xpath, 0);
  1324. }
  1325. /// <summary>Returns the inner text of the node selected by the given XPath query as a 64-bit floating point value,
  1326. /// or the given default value if the node could not be found or was empty.
  1327. /// </summary>
  1328. public static double SelectDouble(this XmlNode node, string xpath, double defaultValue)
  1329. {
  1330. string stringValue = SelectValue(node, xpath);
  1331. return string.IsNullOrEmpty(stringValue) ? defaultValue : XmlConvert.ToDouble(stringValue);
  1332. }
  1333. /// <summary>Returns the inner text of the node selected by the given XPath query as an <see cref="XmlDuration"/>,
  1334. /// or an empty duration if the node could not be found or was empty.
  1335. /// </summary>
  1336. public static XmlDuration SelectDuration(this XmlNode node, string xpath)
  1337. {
  1338. return SelectDuration(node, xpath, XmlDuration.Zero);
  1339. }
  1340. /// <summary>Returns the inner text of the node selected by the given XPath query as an <see cref="XmlDuration"/>,
  1341. /// or the given default value if the node could not be found or was empty.
  1342. /// </summary>
  1343. public static XmlDuration SelectDuration(this XmlNode node, string xpath, XmlDuration defaultValue)
  1344. {
  1345. string stringValue = SelectValue(node, xpath);
  1346. return string.IsNullOrEmpty(stringValue) ? defaultValue : XmlDuration.Parse(stringValue);
  1347. }
  1348. /// <summary>Returns the inner text of the node selected by the given XPath query as a <see cref="Guid"/>,
  1349. /// or <see cref="Guid.Empty"/> if the node could not be found or was empty.
  1350. /// </summary>
  1351. public static Guid SelectGuid(this XmlNode node, string xpath)
  1352. {
  1353. return SelectGuid(node, xpath, Guid.Empty);
  1354. }
  1355. /// <summary>Returns the inner text of the node selected by the given XPath query as a <see cref="Guid"/>,
  1356. /// or the given default value if the node could not be found or was empty.
  1357. /// </summary>
  1358. public static Guid SelectGuid(this XmlNode node, string xpath, Guid defaultValue)
  1359. {
  1360. string stringValue = SelectValue(node, xpath);
  1361. return string.IsNullOrEmpty(stringValue) ? defaultValue : XmlConvert.ToGuid(stringValue);
  1362. }
  1363. /// <summary>Returns the inner text of the node selected by the given XPath query as a 16-bit signed integer,
  1364. /// or 0 if the node could not be found or was empty.
  1365. /// </summary>
  1366. public static short SelectInt16(this XmlNode node, string xpath)
  1367. {
  1368. return SelectInt16(node, xpath, 0);
  1369. }
  1370. /// <summary>Returns the inner text of the node selected by the given XPath query as a 16-bit signed integer,
  1371. /// or the given default value if the node could not be found or was empty.
  1372. /// </summary>
  1373. public static short SelectInt16(this XmlNode node, string xpath, short defaultValue)
  1374. {
  1375. string stringValue = SelectValue(node, xpath);
  1376. return string.IsNullOrEmpty(stringValue) ? defaultValue : XmlConvert.ToInt16(stringValue);
  1377. }
  1378. /// <summary>Returns the inner text of the node selected by the given XPath query as a 32-bit signed integer,
  1379. /// or 0 if the node could not be found or was empty.
  1380. /// </summary>
  1381. public static int SelectInt32(this XmlNode node, string xpath)
  1382. {
  1383. return SelectInt32(node, xpath, 0);
  1384. }
  1385. /// <summary>Returns the inner text of the node selected by the given XPath query as a 32-bit signed integer,
  1386. /// or the given default value if the node could not be found or was empty.
  1387. /// </summary>
  1388. public static int SelectInt32(this XmlNode node, string xpath, int defaultValue)
  1389. {
  1390. string stringValue = SelectValue(node, xpath);
  1391. return string.IsNullOrEmpty(stringValue) ? defaultValue : XmlConvert.ToInt32(stringValue);
  1392. }
  1393. /// <summary>Returns the inner text of the node selected by the given XPath query as a 64-bit signed integer,
  1394. /// or 0 if the node could not be found or was empty.
  1395. /// </summary>
  1396. public static long SelectInt64(this XmlNode node, string xpath)
  1397. {
  1398. return SelectInt64(node, xpath, 0);
  1399. }
  1400. /// <summary>Returns the inner text of the node selected by the given XPath query as a 64-bit signed integer,
  1401. /// or the given default value if the node could not be found or was empty.
  1402. /// </summary>
  1403. public static long SelectInt64(this XmlNode node, string xpath, long defaultValue)
  1404. {
  1405. string stringValue = SelectValue(node, xpath);
  1406. return string.IsNullOrEmpty(stringValue) ? defaultValue : XmlConvert.ToInt64(stringValue);
  1407. }
  1408. /// <summary>Returns the inner text of the node selected by the given XPath query as an 8-bit signed integer,
  1409. /// or 0 if the node could not be found or was empty.
  1410. /// </summary>
  1411. [CLSCompliant(false)]
  1412. public static sbyte SelectSByte(this XmlNode node, string xpath)
  1413. {
  1414. return SelectSByte(node, xpath, 0);
  1415. }
  1416. /// <summary>Returns the inner text of the node selected by the given XPath query as an 8-bit signed integer,
  1417. /// or the given default value if the node could not be found or was empty.
  1418. /// </summary>
  1419. [CLSCompliant(false)]
  1420. public static sbyte SelectSByte(this XmlNode node, string xpath, sbyte defaultValue)
  1421. {
  1422. string stringValue = SelectValue(node, xpath);
  1423. return string.IsNullOrEmpty(stringValue) ? defaultValue : XmlConvert.ToSByte(stringValue);
  1424. }
  1425. /// <summary>Returns the inner text of the node selected by the given XPath query as a 32-bit floating point value,
  1426. /// or 0 if the node could not be found or was empty.
  1427. /// </summary>
  1428. public static float SelectSingle(this XmlNode node, string xpath)
  1429. {
  1430. return SelectSingle(node, xpath, 0);
  1431. }
  1432. /// <summary>Returns the inner text of the node selected by the given XPath query as a 32-bit floating point value,
  1433. /// or the given default value if the node could not be found or was empty.
  1434. /// </summary>
  1435. public static float SelectSingle(this XmlNode node, string xpath, float defaultValue)
  1436. {
  1437. string stringValue = SelectValue(node, xpath);
  1438. return string.IsNullOrEmpty(stringValue) ? defaultValue : XmlConvert.ToSingle(stringValue);
  1439. }
  1440. /// <summary>Returns the trimmed inner text of the node selected by the given XPath query,
  1441. /// or an empty string if the node could not be found.
  1442. /// </summary>
  1443. public static string SelectString(this XmlNode node, string xpath)
  1444. {
  1445. return SelectString(node, xpath, string.Empty);
  1446. }
  1447. /// <summary>Returns the trimmed inner text of the node selected by the given XPath query,
  1448. /// or the given default value if the node could not be found.
  1449. /// </summary>
  1450. public static string SelectString(this XmlNode node, string xpath, string defaultValue)
  1451. {
  1452. string stringValue = SelectValue(node, xpath);
  1453. return string.IsNullOrEmpty(stringValue) ? defaultValue : stringValue;
  1454. }
  1455. /// <summary>Returns the inner text of the node selected by the given XPath query as a <see cref="TimeSpan"/>,
  1456. /// or an empty timespan if the node could not be found or was empty.
  1457. /// </summary>
  1458. public static TimeSpan SelectTimeSpan(this XmlNode node, string xpath)
  1459. {
  1460. return SelectTimeSpan(node, xpath, new TimeSpan());
  1461. }
  1462. /// <summary>Returns the inner text of the node selected by the given XPath query as a <see cref="TimeSpan"/>,
  1463. /// or the given default value if the node could not be found or was empty.
  1464. /// </summary>
  1465. public static TimeSpan SelectTimeSpan(this XmlNode node, string xpath, TimeSpan defaultValue)
  1466. {
  1467. string stringValue = SelectValue(node, xpath);
  1468. return string.IsNullOrEmpty(stringValue) ? defaultValue : XmlConvert.ToTimeSpan(stringValue);
  1469. }
  1470. /// <summary>Returns the inner text of the node selected by the given XPath query as a 16-bit unsigned integer,
  1471. /// or 0 if the node could not be found or was empty.
  1472. /// </summary>
  1473. [CLSCompliant(false)]
  1474. public static ushort SelectUInt16(this XmlNode node, string xpath)
  1475. {
  1476. return SelectUInt16(node, xpath, 0);
  1477. }
  1478. /// <summary>Returns the inner text of the node selected by the given XPath query as a 16-bit unsigned integer,
  1479. /// or the given default value if the node could not be found or was empty.
  1480. /// </summary>
  1481. [CLSCompliant(false)]
  1482. public static ushort SelectUInt16(this XmlNode node, string xpath, ushort defaultValue)
  1483. {
  1484. string stringValue = SelectValue(node, xpath);
  1485. return string.IsNullOrEmpty(stringValue) ? defaultValue : XmlConvert.ToUInt16(stringValue);
  1486. }
  1487. /// <summary>Returns the inner text of the node selected by the given XPath query as a 32-bit unsigned integer,
  1488. /// or 0 if the node could not be found or was empty.
  1489. /// </summary>
  1490. [CLSCompliant(false)]
  1491. public static uint SelectUInt32(this XmlNode node, string xpath)
  1492. {
  1493. return SelectUInt32(node, xpath, 0);
  1494. }
  1495. /// <summary>Returns the inner text of the node selected by the given XPath query as a 32-bit unsigned integer,
  1496. /// or the given default value if the node could not be found or was empty.
  1497. /// </summary>
  1498. [CLSCompliant(false)]
  1499. public static uint SelectUInt32(this XmlNode node, string xpath, uint defaultValue)
  1500. {
  1501. string stringValue = SelectValue(node, xpath);
  1502. return string.IsNullOrEmpty(stringValue) ? defaultValue : XmlConvert.ToUInt32(stringValue);
  1503. }
  1504. /// <summary>Returns the inner text of the node selected by the given XPath query as a 64-bit unsigned integer,
  1505. /// or 0 if the node could not be found or was empty.
  1506. /// </summary>
  1507. [CLSCompliant(false)]
  1508. public static ulong SelectUInt64(this XmlNode node, string xpath)
  1509. {
  1510. return SelectUInt64(node, xpath, 0);
  1511. }
  1512. /// <summary>Returns the inner text of the node selected by the given XPath query as a 64-bit unsigned integer,
  1513. /// or the given default value if the node could not be found or was empty.
  1514. /// </summary>
  1515. [CLSCompliant(false)]
  1516. public static ulong SelectUInt64(this XmlNode node, string xpath, ulong defaultValue)
  1517. {
  1518. string stringValue = SelectValue(node, xpath);
  1519. return string.IsNullOrEmpty(stringValue) ? defaultValue : XmlConvert.ToUInt64(stringValue);
  1520. }
  1521. /// <summary>Returns the trimmed inner text of the node selected by the given XPath query,
  1522. /// or null if the node could not be found.
  1523. /// </summary>
  1524. public static string SelectValue(this XmlNode node, string xpath)
  1525. {
  1526. return SelectValue(node, xpath, null);
  1527. }
  1528. /// <summary>Returns the trimmed inner text of the node selected by the given XPath query, or
  1529. /// the given default value if the node could not be found.
  1530. /// </summary>
  1531. public static string SelectValue(this XmlNode node, string xpath, string defaultValue)
  1532. {
  1533. if(node == null) return defaultValue;
  1534. XmlNode selectedNode = node.SelectSingleNode(xpath);
  1535. return selectedNode == null ? defaultValue : selectedNode.InnerText.Trim();
  1536. }
  1537. /// <summary>Gets the named <see cref="XmlAttribute"/> from the given node, or null if the node is null.</summary>
  1538. static XmlAttribute GetAttributeNode(this XmlNode node, string attrName)
  1539. {
  1540. return node == null || node.Attributes == null ? null : node.Attributes[attrName];
  1541. }
  1542. /// <summary>Gets the named <see cref="XmlAttribute"/> from the given node, or null if the node is null.</summary>
  1543. static XmlAttribute GetAttributeNode(this XmlNode node, string localName, string namespaceUri)
  1544. {
  1545. return node == null || node.Attributes == null ? null : node.Attributes[localName, namespaceUri];
  1546. }
  1547. }
  1548. #endregion
  1549. #region XmlQualifiedNameExtensions
  1550. /// <summary>Provides useful extensions to the <see cref="XmlQualifiedName"/> class.</summary>
  1551. public static class XmlQualifiedNameExtensions
  1552. {
  1553. /// <summary>Converts an <see cref="XmlQualifiedName"/> into a <c>localName</c>, <c>prefix:localName</c> <c>namespaceUri:localName</c>
  1554. /// form valid in the context of the given node.
  1555. /// </summary>
  1556. public static string ToString(this XmlQualifiedName qname, XmlNode context)
  1557. {
  1558. if(qname == null || context == null) throw new ArgumentNullException();
  1559. // if qname is not actually a qualified name, we can't necessarily translate it
  1560. if(string.IsNullOrEmpty(qname.Namespace))
  1561. {
  1562. if(!string.IsNullOrEmpty(context.GetNamespaceOfPrefix(""))) // if simply using the local name wouldn't result in the same thing...
  1563. {
  1564. throw new ArgumentException("The qname has no namespace, and a default namespace has been set in the given context.");
  1565. }
  1566. return qname.Name;
  1567. }
  1568. string prefix = context.GetPrefixOfNamespace(qname.Namespace);
  1569. if(string.IsNullOrEmpty(prefix))
  1570. {
  1571. // unfortunately, the method returns an empty string for both the default namespace and an undeclared namespace. if it's actually
  1572. // undeclared, then use the namespace URI
  1573. if(!qname.Namespace.OrdinalEquals(context.GetNamespaceOfPrefix(""))) prefix = qname.Namespace;
  1574. }
  1575. return string.IsNullOrEmpty(prefix) ? qname.Name : prefix + ":" + qname.Name;
  1576. }
  1577. /// <summary>Converts an <see cref="XmlQualifiedName"/> into a <c>localName</c>, <c>prefix:localName</c> <c>namespaceUri:localName</c>
  1578. /// form valid in the context of the given namespace resolver.
  1579. /// </summary>
  1580. public static string ToString(this XmlQualifiedName qname, IXmlNamespaceResolver resolver)
  1581. {
  1582. if(qname == null || resolver == null) throw new ArgumentNullException();
  1583. // if qname is not actually a qualified name, we can't necessarily translate it
  1584. if(string.IsNullOrEmpty(qname.Namespace))
  1585. {
  1586. if(!string.IsNullOrEmpty(resolver.LookupNamespace(""))) // if simply using the local name wouldn't result in the same thing...
  1587. {
  1588. throw new ArgumentException("The qname has no namespace, and a default namespace has been set in the given context.");
  1589. }
  1590. return qname.Name;
  1591. }
  1592. string prefix = resolver.LookupPrefix(qname.Namespace);
  1593. if(prefix == null) prefix = qname.Namespace;
  1594. return string.IsNullOrEmpty(prefix) ? qname.Name : prefix + ":" + qname.Name;
  1595. }
  1596. /// <summary>Ensures that the given qualified name has a valid namespace URI and local name. Empty names are allowed.</summary>
  1597. /// <exception cref="ArgumentNullException">Thrown if <paramref name="qname"/> is null.</exception>
  1598. /// <exception cref="FormatException">Thrown if <paramref name="qname"/> does not have a valid format.</exception>
  1599. public static void Validate(this XmlQualifiedName qname)
  1600. {
  1601. if(qname == null) throw new ArgumentNullException();
  1602. try
  1603. {
  1604. if(!string.IsNullOrEmpty(qname.Namespace)) new Uri(qname.Namespace, UriKind.Absolute);
  1605. if(!string.IsNullOrEmpty(qname.Name)) XmlConvert.VerifyNCName(qname.Name);
  1606. }
  1607. catch(UriFormatException ex)
  1608. {
  1609. throw new FormatException("The QName " + qname.ToString() + " does not have a valid namespace URI. " + ex.Message);
  1610. }
  1611. catch(XmlException ex)
  1612. {
  1613. throw new FormatException("The QName " + qname.ToString() + " does not have a valid local name. " + ex.Message);
  1614. }
  1615. }
  1616. }
  1617. #endregion
  1618. #region XmlReaderExtensions
  1619. /// <summary>Provides extensions to the <see cref="XmlReader"/> class.</summary>
  1620. public static class XmlReaderExtensions
  1621. {
  1622. /// <summary>Returns the value of the named attribute, or <c>default(T)</c> if the attribute was unspecified.</summary>
  1623. public static T GetAttribute<T>(this XmlReader reader, string attrName, Converter<string, T> converter)
  1624. {
  1625. return GetAttribute<T>(reader, attrName, converter, default(T));
  1626. }
  1627. /// <summary>Returns the value of the named attribute, or the given default value if the attribute was unspecified.</summary>
  1628. public static T GetAttribute<T>(this XmlReader reader, string attrName, Converter<string, T> converter,
  1629. T defaultValue)
  1630. {
  1631. if(reader == null || converter == null) throw new ArgumentNullException();
  1632. string value = reader.GetAttribute(attrName);
  1633. return value == null ? defaultValue : converter(value);
  1634. }
  1635. /// <summary>Returns the value of the named attribute as a boolean, or false if the attribute was unspecified or empty.</summary>
  1636. public static bool GetBoolAttribute(this XmlReader reader, string attrName)
  1637. {
  1638. return GetBoolAttribute(reader, attrName, false);
  1639. }
  1640. /// <summary>Returns the value of the named attribute as a boolean, or the given
  1641. /// default value if the attribute was unspecified or empty.
  1642. /// </summary>
  1643. public static bool GetBoolAttribute(this XmlReader reader, string attrName, bool defaultValue)
  1644. {
  1645. string attrValue = GetAttributeValue(reader, attrName);
  1646. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToBoolean(attrValue);
  1647. }
  1648. /// <summary>Returns the value of the named attribute as a byte, or 0 if the attribute was unspecified or empty.</summary>
  1649. public static byte GetByteAttribute(this XmlReader reader, string attrName)
  1650. {
  1651. return GetByteAttribute(reader, attrName, 0);
  1652. }
  1653. /// <summary>Returns the value of the named attribute as a byte, or the given default
  1654. /// value if the attribute was unspecified or empty.
  1655. /// </summary>
  1656. public static byte GetByteAttribute(this XmlReader reader, string attrName, byte defaultValue)
  1657. {
  1658. string attrValue = GetAttributeValue(reader, attrName);
  1659. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToByte(attrValue);
  1660. }
  1661. /// <summary>Returns the value of the named attribute as a character, or the nul character if the attribute was unspecified or empty.</summary>
  1662. public static char GetCharAttribute(this XmlReader reader, string attrName)
  1663. {
  1664. return GetCharAttribute(reader, attrName, '\0');
  1665. }
  1666. /// <summary>Returns the value of the named attribute as a character, or the given default
  1667. /// value if the attribute was unspecified or empty.
  1668. /// </summary>
  1669. public static char GetCharAttribute(this XmlReader reader, string attrName, char defaultValue)
  1670. {
  1671. string attrValue = GetAttributeValue(reader, attrName);
  1672. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToChar(attrValue);
  1673. }
  1674. /// <summary>Returns the value of the named attribute as a nullable datetime, or null if the attribute was unspecified or empty.</summary>
  1675. public static DateTime? GetDateTimeAttribute(this XmlReader reader, string attrName)
  1676. {
  1677. return GetDateTimeAttribute(reader, attrName, (DateTime?)null);
  1678. }
  1679. /// <summary>Returns the value of the named attribute as a nullable datetime, or the given default
  1680. /// value if the attribute was unspecified or empty.
  1681. /// </summary>
  1682. public static DateTime? GetDateTimeAttribute(this XmlReader reader, string attrName, DateTime? defaultValue)
  1683. {
  1684. string attrValue = GetAttributeValue(reader, attrName);
  1685. return string.IsNullOrEmpty(attrValue) ?
  1686. defaultValue : XmlConvert.ToDateTime(attrValue, XmlDateTimeSerializationMode.Unspecified);
  1687. }
  1688. /// <summary>Returns the value of the named attribute as a decimal, or 0 if the attribute was unspecified or empty.</summary>
  1689. public static decimal GetDecimalAttribute(this XmlReader reader, string attrName)
  1690. {
  1691. return GetDecimalAttribute(reader, attrName, 0);
  1692. }
  1693. /// <summary>Returns the value of the named attribute as a decimal, or the given default
  1694. /// value if the attribute was unspecified or empty.
  1695. /// </summary>
  1696. public static decimal GetDecimalAttribute(this XmlReader reader, string attrName, decimal defaultValue)
  1697. {
  1698. string attrValue = GetAttributeValue(reader, attrName);
  1699. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToDecimal(attrValue);
  1700. }
  1701. /// <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>
  1702. public static double GetDoubleAttribute(this XmlReader reader, string attrName)
  1703. {
  1704. return GetDoubleAttribute(reader, attrName, 0);
  1705. }
  1706. /// <summary>Returns the value of the named attribute as a 64-bit floating point value, or the given default
  1707. /// value if the attribute was unspecified or empty.
  1708. /// </summary>
  1709. public static double GetDoubleAttribute(this XmlReader reader, string attrName, double defaultValue)
  1710. {
  1711. string attrValue = GetAttributeValue(reader, attrName);
  1712. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToDouble(attrValue);
  1713. }
  1714. /// <summary>Returns the value of the named attribute as a <see cref="Guid"/>, or <see cref="Guid.Empty" />
  1715. /// if the attribute was unspecified or empty.
  1716. /// </summary>
  1717. public static Guid GetGuidAttribute(this XmlReader reader, string attrName)
  1718. {
  1719. return GetGuidAttribute(reader, attrName, Guid.Empty);
  1720. }
  1721. /// <summary>Returns the value of the named attribute as a <see cref="Guid"/>, or the given default
  1722. /// value if the attribute was unspecified or empty.
  1723. /// </summary>
  1724. public static Guid GetGuidAttribute(this XmlReader reader, string attrName, Guid defaultValue)
  1725. {
  1726. string attrValue = GetAttributeValue(reader, attrName);
  1727. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToGuid(attrValue);
  1728. }
  1729. /// <summary>Returns the value of the named attribute as a 16-bit signed integer, or 0 if the attribute was unspecified or empty.</summary>
  1730. public static short GetInt16Attribute(this XmlReader reader, string attrName)
  1731. {
  1732. return GetInt16Attribute(reader, attrName, 0);
  1733. }
  1734. /// <summary>Returns the value of the named attribute as a 16-bit signed integer, or the given default
  1735. /// value if the attribute was unspecified or empty.
  1736. /// </summary>
  1737. public static short GetInt16Attribute(this XmlReader reader, string attrName, short defaultValue)
  1738. {
  1739. string attrValue = GetAttributeValue(reader, attrName);
  1740. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToInt16(attrValue);
  1741. }
  1742. /// <summary>Returns the value of the named attribute as a 32-bit signed integer, or 0 if the attribute was unspecified or empty.</summary>
  1743. public static int GetInt32Attribute(this XmlReader reader, string attrName)
  1744. {
  1745. return GetInt32Attribute(reader, attrName, 0);
  1746. }
  1747. /// <summary>Returns the value of the named attribute as a 32-bit signed integer, or the given default
  1748. /// value if the attribute was unspecified or empty.
  1749. /// </summary>
  1750. public static int GetInt32Attribute(this XmlReader reader, string attrName, int defaultValue)
  1751. {
  1752. string attrValue = GetAttributeValue(reader, attrName);
  1753. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToInt32(attrValue);
  1754. }
  1755. /// <summary>Returns the value of the named attribute as a 64-bit signed integer, or 0 if the attribute was unspecified or empty.</summary>
  1756. public static long GetInt64Attribute(this XmlReader reader, string attrName)
  1757. {
  1758. return GetInt64Attribute(reader, attrName, 0);
  1759. }
  1760. /// <summary>Returns the value of the named attribute as a 64-bit signed integer, or the given default
  1761. /// value if the attribute was unspecified or empty.
  1762. /// </summary>
  1763. public static long GetInt64Attribute(this XmlReader reader, string attrName, long defaultValue)
  1764. {
  1765. string attrValue = GetAttributeValue(reader, attrName);
  1766. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToInt64(attrValue);
  1767. }
  1768. /// <summary>Returns the <see cref="XmlQualifiedName"/> for reader's current element.</summary>
  1769. public static XmlQualifiedName GetQualifiedName(this XmlReader reader)
  1770. {
  1771. if(reader == null) throw new ArgumentNullException();
  1772. if(reader.NodeType != XmlNodeType.Element && reader.NodeType != XmlNodeType.EndElement)
  1773. {
  1774. throw new InvalidOperationException("The reader must be positioned on an element.");
  1775. }
  1776. return new XmlQualifiedName(reader.LocalName, reader.NamespaceURI);
  1777. }
  1778. /// <summary>Returns the value of the named attribute as an 8-bit signed integer, or 0 if the attribute was unspecified or empty.</summary>
  1779. [CLSCompliant(false)]
  1780. public static sbyte GetSByteAttribute(this XmlReader reader, string attrName)
  1781. {
  1782. return GetSByteAttribute(reader, attrName, 0);
  1783. }
  1784. /// <summary>Returns the value of the named attribute as an 8-bit signed integer, or the given default
  1785. /// value if the attribute was unspecified or empty.
  1786. /// </summary>
  1787. [CLSCompliant(false)]
  1788. public static sbyte GetSByteAttribute(this XmlReader reader, string attrName, sbyte defaultValue)
  1789. {
  1790. string attrValue = GetAttributeValue(reader, attrName);
  1791. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToSByte(attrValue);
  1792. }
  1793. /// <summary>Returns the value of the named attribute as a 32-bit floating point value, or 0 if the attribute was unspecified or empty.</summary>
  1794. public static float GetSingleAttribute(this XmlReader reader, string attrName)
  1795. {
  1796. return GetSingleAttribute(reader, attrName, 0);
  1797. }
  1798. /// <summary>Returns the value of the named attribute as a 32-bit floating point value, or the given default
  1799. /// value if the attribute was unspecified or empty.
  1800. /// </summary>
  1801. public static float GetSingleAttribute(this XmlReader reader, string attrName, float defaultValue)
  1802. {
  1803. string attrValue = GetAttributeValue(reader, attrName);
  1804. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToSingle(attrValue);
  1805. }
  1806. /// <summary>Returns the value of the named attribute as a string, or the empty string if the attribute was unspecified or empty.</summary>
  1807. public static string GetStringAttribute(this XmlReader reader, string attrName)
  1808. {
  1809. return GetStringAttribute(reader, attrName, string.Empty);
  1810. }
  1811. /// <summary>Returns the value of the named attribute as a string, or the given default
  1812. /// value if the attribute was unspecified or empty.
  1813. /// </summary>
  1814. public static string GetStringAttribute(this XmlReader reader, string attrName, string defaultValue)
  1815. {
  1816. string attrValue = GetAttributeValue(reader, attrName);
  1817. return string.IsNullOrEmpty(attrValue) ? defaultValue : attrValue;
  1818. }
  1819. /// <summary>Returns the value of the named attribute as a <see cref="TimeSpan"/>, or
  1820. /// an empty timespan if the attribute was unspecified or empty.
  1821. /// </summary>
  1822. public static TimeSpan GetTimeSpanAttribute(this XmlReader reader, string attrName)
  1823. {
  1824. return GetTimeSpanAttribute(reader, attrName, new TimeSpan());
  1825. }
  1826. /// <summary>Returns the value of the named attribute as a <see cref="TimeSpan"/>, or
  1827. /// the given default value if the attribute was unspecified or empty.
  1828. /// </summary>
  1829. public static TimeSpan GetTimeSpanAttribute(this XmlReader reader, string attrName, TimeSpan defaultValue)
  1830. {
  1831. string attrValue = GetAttributeValue(reader, attrName);
  1832. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToTimeSpan(attrValue);
  1833. }
  1834. /// <summary>Returns the value of the named attribute as a 16-bit unsigned integer, or 0 if the attribute was unspecified or empty.</summary>
  1835. [CLSCompliant(false)]
  1836. public static ushort GetUInt16Attribute(this XmlReader reader, string attrName)
  1837. {
  1838. return GetUInt16Attribute(reader, attrName, 0);
  1839. }
  1840. /// <summary>Returns the value of the named attribute as a 16-bit unsigned integer, or the given default
  1841. /// value if the attribute was unspecified or empty.
  1842. /// </summary>
  1843. [CLSCompliant(false)]
  1844. public static ushort GetUInt16Attribute(this XmlReader reader, string attrName, ushort defaultValue)
  1845. {
  1846. string attrValue = GetAttributeValue(reader, attrName);
  1847. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToUInt16(attrValue);
  1848. }
  1849. /// <summary>Returns the value of the named attribute as a 32-bit unsigned integer, or 0 if the attribute was unspecified or empty.</summary>
  1850. [CLSCompliant(false)]
  1851. public static uint GetUInt32Attribute(this XmlReader reader, string attrName)
  1852. {
  1853. return GetUInt32Attribute(reader, attrName, 0);
  1854. }
  1855. /// <summary>Returns the value of the named attribute as a 32-bit unsigned integer, or the given default
  1856. /// value if the attribute was unspecified or empty.
  1857. /// </summary>
  1858. [CLSCompliant(false)]
  1859. public static uint GetUInt32Attribute(this XmlReader reader, string attrName, uint defaultValue)
  1860. {
  1861. string attrValue = GetAttributeValue(reader, attrName);
  1862. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToUInt32(attrValue);
  1863. }
  1864. /// <summary>Returns the value of the named attribute as a 64-bit unsigned integer, or 0 if the attribute was unspecified or empty.</summary>
  1865. [CLSCompliant(false)]
  1866. public static ulong GetUInt64Attribute(this XmlReader reader, string attrName)
  1867. {
  1868. return GetUInt64Attribute(reader, attrName, 0);
  1869. }
  1870. /// <summary>Returns the value of the named attribute as a 64-bit unsigned integer, or the given default
  1871. /// value if the attribute was unspecified or empty.
  1872. /// </summary>
  1873. [CLSCompliant(false)]
  1874. public static ulong GetUInt64Attribute(this XmlReader reader, string attrName, ulong defaultValue)
  1875. {
  1876. string attrValue = GetAttributeValue(reader, attrName);
  1877. return string.IsNullOrEmpty(attrValue) ? defaultValue : XmlConvert.ToUInt64(attrValue);
  1878. }
  1879. /// <summary>Determines whether the qualified name of the current element equals the given qualified name.</summary>
  1880. public static bool HasName(this XmlReader reader, XmlQualifiedName qname)
  1881. {
  1882. if(qname == null) throw new ArgumentNullException();
  1883. return reader.HasName(qname.Name, qname.Namespace);
  1884. }
  1885. /// <summary>Determines whether the qualified name of the current element equals the given qualified name.</summary>
  1886. public static bool HasName(this XmlReader reader, string localName, string namespaceUri)
  1887. {
  1888. if(reader == null) throw new ArgumentNullException();
  1889. if(string.IsNullOrEmpty(localName) || namespaceUri == null)
  1890. {
  1891. throw new ArgumentException("Local name must not be empty and namespace URI must not be null.");
  1892. }
  1893. return localName.OrdinalEquals(reader.LocalName) && namespaceUri.OrdinalEquals(reader.NamespaceURI);
  1894. }
  1895. /// <summary>Parses a qualified name (i.e. a name of the form <c>prefix:localName</c> or <c>namespaceUri:localName</c>) into an
  1896. /// <see cref="XmlQualifiedName"/> in the context of the current reader. This method also accepts local names.
  1897. /// </summary>
  1898. public static XmlQualifiedName ParseQualifiedName(this XmlReader reader, string qualifiedName)
  1899. {
  1900. if(reader == null) throw new ArgumentNullException();
  1901. return string.IsNullOrEmpty(qualifiedName) ?
  1902. XmlQualifiedName.Empty : XmlUtility.ParseQualifiedName(qualifiedName, reader.LookupNamespace);
  1903. }
  1904. /// <summary>Calls <see cref="XmlReader.Read"/> until <see cref="XmlReader.NodeType"/> is no longer equal to
  1905. /// <see cref="XmlNodeType.Whitespace"/>, and returns the value of the last call to <see cref="XmlReader.Read"/>.
  1906. /// </summary>
  1907. public static bool ReadPastWhitespace(this XmlReader reader)
  1908. {
  1909. if(reader == null) throw new ArgumentNullException();
  1910. while(reader.Read())
  1911. {
  1912. if(reader.NodeType != XmlNodeType.Whitespace) return true;
  1913. }
  1914. return false;
  1915. }
  1916. /// <summary>Skips the children of the current element, without skipping the end element.</summary>
  1917. public static void SkipChildren(this XmlReader reader)
  1918. {
  1919. if(reader == null) throw new ArgumentNullException();
  1920. if(reader.NodeType != XmlNodeType.Element) throw new InvalidOperationException();
  1921. if(!reader.IsEmptyElement)
  1922. {
  1923. reader.Read();
  1924. while(reader.NodeType != XmlNodeType.EndElement) reader.Skip();
  1925. }
  1926. }
  1927. /// <summary>Skips nodes that are not <see cref="XmlNodeType.EndElement"/> nodes or empty elements.</summary>
  1928. public static void SkipToEnd(this XmlReader reader)
  1929. {
  1930. if(reader == null) throw new ArgumentNullException();
  1931. while(reader.NodeType != XmlNodeType.EndElement && !reader.IsEmptyElement) reader.Skip();
  1932. }
  1933. /// <summary>Skips <see cref="XmlNodeType.Whitespace"/> nodes (but not <see cref="XmlNodeType.SignificantWhitespace"/> nodes).</summary>
  1934. public static void SkipWhiteSpace(this XmlReader reader)
  1935. {
  1936. if(reader == null) throw new ArgumentNullException();
  1937. while(reader.NodeType == XmlNodeType.Whitespace) reader.Read();
  1938. }
  1939. /// <summary>Returns the value of the named attribute, or null if the attribute was unspecified.</summary>
  1940. static string GetAttributeValue(this XmlReader reader, string attrName)
  1941. {
  1942. if(reader == null) throw new ArgumentNullException();
  1943. return reader.GetAttribute(attrName);
  1944. }
  1945. }
  1946. #endregion
  1947. #region XmlWriterExtensions
  1948. /// <summary>Provides extensions to the <see cref="XmlWriter"/> class.</summary>
  1949. public static class XmlWriterExtensions
  1950. {
  1951. /// <summary>Writes the named attribute with content based on a boolean.</summary>
  1952. public static void WriteAttribute(this XmlWriter writer, string localName, bool value)
  1953. {
  1954. if(writer == null) throw new ArgumentNullException();
  1955. writer.WriteAttributeString(localName, XmlConvert.ToString(value));
  1956. }
  1957. /// <summary>Writes the named attribute with content based on a byte.</summary>
  1958. public static void WriteAttribute(this XmlWriter writer, string localName, byte value)
  1959. {
  1960. if(writer == null) throw new ArgumentNullException();
  1961. writer.WriteAttributeString(localName, XmlConvert.ToString(value));
  1962. }
  1963. /// <summary>Writes the named attribute with content based on a character.</summary>
  1964. public static void WriteAttribute(this XmlWriter writer, string localName, char value)
  1965. {
  1966. if(writer == null) throw new ArgumentNullException();
  1967. writer.WriteAttributeString(localName, XmlConvert.ToString(value));
  1968. }
  1969. /// <summary>Writes the named attribute with content based on a <see cref="DateTime"/>. The <see cref="DateTimeKind"/> of the
  1970. /// <see cref="DateTime"/> will be preserved.
  1971. /// </summary>
  1972. public static void WriteAttribute(this XmlWriter writer, string localName, DateTime value)
  1973. {
  1974. writer.WriteAttribute(localName, value, XmlDateTimeSerializationMode.RoundtripKind);
  1975. }
  1976. /// <summary>Writes the named attribute with content based on a <see cref="DateTime"/>.</summary>
  1977. public static void WriteAttribute(this XmlWriter writer, string localName, DateTime value, XmlDateTimeSerializationMode mode)
  1978. {
  1979. if(writer == null) throw new ArgumentNullException();
  1980. writer.WriteAttributeString(localName, XmlConvert.ToString(value, mode));
  1981. }
  1982. /// <summary>Writes the named attribute with content based on a <see cref="Decimal"/>.</summary>
  1983. public static void WriteAttribute(this XmlWriter writer, string localName, decimal value)
  1984. {
  1985. if(writer == null) throw new ArgumentNullException();
  1986. writer.WriteAttributeString(localName, XmlConvert.ToString(value));
  1987. }
  1988. /// <summary>Writes the named attribute with content based on a 64-bit floating point value.</summary>
  1989. public static void WriteAttribute(this XmlWriter writer, string localName, double value)
  1990. {
  1991. if(writer == null) throw new ArgumentNullException();
  1992. writer.WriteAttributeString(localName, XmlConvert.ToString(value));
  1993. }
  1994. /// <summary>Writes the named attribute with content based on a <see cref="Guid"/>.</summary>
  1995. public static void WriteAttribute(this XmlWriter writer, string localName, Guid value)
  1996. {
  1997. if(writer == null) throw new ArgumentNullException();
  1998. writer.WriteAttributeString(localName, XmlConvert.ToString(value));
  1999. }
  2000. /// <summary>Writes the named attribute with content based on a 16-bit integer.</summary>
  2001. public static void WriteAttribute(this XmlWriter writer, string localName, short value)
  2002. {
  2003. if(writer == null) throw new ArgumentNullException();
  2004. writer.WriteAttributeString(localName, XmlConvert.ToString(value));
  2005. }
  2006. /// <summary>Writes the named attribute with content based on a 32-bit integer.</summary>
  2007. public static void WriteAttribute(this XmlWriter writer, string localName, int value)
  2008. {
  2009. if(writer == null) throw new ArgumentNullException();
  2010. writer.WriteAttributeString(localName, XmlConvert.ToString(value));
  2011. }
  2012. /// <summary>Writes the named attribute with content based on a 64-bit integer.</summary>
  2013. public static void WriteAttribute(this XmlWriter writer, string localName, long value)
  2014. {
  2015. if(writer == null) throw new ArgumentNullException();
  2016. writer.WriteAttributeString(localName, XmlConvert.ToString(value));
  2017. }
  2018. /// <summary>Writes the named attribute with content based on an 8-bit integer.</summary>
  2019. [CLSCompliant(false)]
  2020. public static void WriteAttribute(this XmlWriter writer, string localName, sbyte value)
  2021. {
  2022. if(writer == null) throw new ArgumentNullException();
  2023. writer.WriteAttributeString(localName, XmlConvert.ToString(value));
  2024. }
  2025. /// <summary>Writes the named attribute with content based on an 32-bit floating point value.</summary>
  2026. public static void WriteAttribute(this XmlWriter writer, string localName, float value)
  2027. {
  2028. if(writer == null) throw new ArgumentNullException();
  2029. writer.WriteAttributeString(localName, XmlConvert.ToString(value));
  2030. }
  2031. /// <summary>Writes the named attribute with content based on an <see cref="TimeSpan"/>.</summary>
  2032. public static void WriteAttribute(this XmlWriter writer, string localName, TimeSpan value)
  2033. {
  2034. if(writer == null) throw new ArgumentNullException();
  2035. writer.WriteAttributeString(localName, XmlConvert.ToString(value));
  2036. }
  2037. /// <summary>Writes the named attribute with content based on a 16-bit unsigned integer.</summary>
  2038. [CLSCompliant(false)]
  2039. public static void WriteAttribute(this XmlWriter writer, string localName, ushort value)
  2040. {
  2041. if(writer == null) throw new ArgumentNullException();
  2042. writer.WriteAttributeString(localName, XmlConvert.ToString(value));
  2043. }
  2044. /// <summary>Writes the named attribute with content based on a 32-bit unsigned integer.</summary>
  2045. [CLSCompliant(false)]
  2046. public static void WriteAttribute(this XmlWriter writer, string localName, uint value)
  2047. {
  2048. if(writer == null) throw new ArgumentNullException();
  2049. writer.WriteAttributeString(localName, XmlConvert.ToString(value));
  2050. }
  2051. /// <summary>Writes the named attribute with content based on a 64-bit unsigned integer.</summary>
  2052. [CLSCompliant(false)]
  2053. public static void WriteAttribute(this XmlWriter writer, string localName, ulong value)
  2054. {
  2055. if(writer == null) throw new ArgumentNullException();
  2056. writer.WriteAttributeString(localName, XmlConvert.ToString(value));
  2057. }
  2058. /// <summary>Writes an element with content based on an <see cref="XmlDuration"/> value.</summary>
  2059. public static void WriteAttribute(this XmlWriter writer, string localName, XmlDuration value)
  2060. {
  2061. if(writer == null) throw new ArgumentNullException();
  2062. writer.WriteAttributeString(localName, value.ToString());
  2063. }
  2064. /// <summary>Writes an attribute with the given qualified name and value.</summary>
  2065. public static void WriteAttributeString(this XmlWriter writer, XmlQualifiedName qname, string value)
  2066. {
  2067. if(writer == null || qname == null) throw new ArgumentNullException();
  2068. writer.WriteAttributeString(qname.Name, qname.Namespace, value);
  2069. }
  2070. /// <summary>Writes an element with content based on the date portion of a <see cref="DateTime"/> value.</summary>
  2071. public static void WriteDate(this XmlWriter writer, DateTime date)
  2072. {
  2073. if(writer == null) throw new ArgumentNullException();
  2074. writer.WriteString(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
  2075. }
  2076. /// <summary>Writes an element with content based on the date portion of a <see cref="DateTime"/> value.</summary>
  2077. public static void WriteDateElement(this XmlWriter writer, string localName, DateTime date)
  2078. {
  2079. if(writer == null) throw new ArgumentNullException();
  2080. writer.WriteElementString(localName, date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
  2081. }
  2082. /// <summary>Writes the named element with content based on a boolean.</summary>
  2083. public static void WriteElement(this XmlWriter writer, string localName, bool value)
  2084. {
  2085. if(writer == null) throw new ArgumentNullException();
  2086. writer.WriteElementString(localName, XmlConvert.ToString(value));
  2087. }
  2088. /// <summary>Writes the named element with content based on a byte.</summary>
  2089. public static void WriteElement(this XmlWriter writer, string localName, byte value)
  2090. {
  2091. if(writer == null) throw new ArgumentNullException();
  2092. writer.WriteElementString(localName, XmlConvert.ToString(value));
  2093. }
  2094. /// <summary>Writes the named element with content based on a character.</summary>
  2095. public static void WriteElement(this XmlWriter writer, string localName, char value)
  2096. {
  2097. if(writer == null) throw new ArgumentNullException();
  2098. writer.WriteElementString(localName, XmlConvert.ToString(value));
  2099. }
  2100. /// <summary>Writes the named element with content based on a <see cref="DateTime"/>. The <see cref="DateTimeKind"/> of the
  2101. /// <see cref="DateTime"/> will be preserved.
  2102. /// </summary>
  2103. public static void WriteElement(this XmlWriter writer, string localName, DateTime value)
  2104. {
  2105. writer.WriteElement(localName, value, XmlDateTimeSerializationMode.RoundtripKind);
  2106. }
  2107. /// <summary>Writes the named element with content based on a <see cref="DateTime"/>.</summary>
  2108. public static void WriteElement(this XmlWriter writer, string localName, DateTime value, XmlDateTimeSerializationMode mode)
  2109. {
  2110. if(writer == null) throw new ArgumentNullException();
  2111. writer.WriteElementString(localName, XmlConvert.ToString(value, mode));
  2112. }
  2113. /// <summary>Writes the named element with content based on a <see cref="Decimal"/>.</summary>
  2114. public static void WriteElement(this XmlWriter writer, string localName, decimal value)
  2115. {
  2116. if(writer == null) throw new ArgumentNullException();
  2117. writer.WriteElementString(localName, XmlConvert.ToString(value));
  2118. }
  2119. /// <summary>Writes the named element with content based on a 64-bit floating point value.</summary>
  2120. public static void WriteElement(this XmlWriter writer, string localName, double value)
  2121. {
  2122. if(writer == null) throw new ArgumentNullException();
  2123. writer.WriteElementString(localName, XmlConvert.ToString(value));
  2124. }
  2125. /// <summary>Writes the named element with content based on a <see cref="Guid"/>.</summary>
  2126. public static void WriteElement(this XmlWriter writer, string localName, Guid value)
  2127. {
  2128. if(writer == null) throw new ArgumentNullException();
  2129. writer.WriteElementString(localName, XmlConvert.ToString(value));
  2130. }
  2131. /// <summary>Writes the named element with content based on a 16-bit integer.</summary>
  2132. public static void WriteElement(this XmlWriter writer, string localName, short value)
  2133. {
  2134. if(writer == null) throw new ArgumentNullException();
  2135. writer.WriteElementString(localName, XmlConvert.ToString(value));
  2136. }
  2137. /// <summary>Writes the named element with content based on a 32-bit integer.</summary>
  2138. public static void WriteElement(this XmlWriter writer, string localName, int value)
  2139. {
  2140. if(writer == null) throw new ArgumentNullException();
  2141. writer.WriteElementString(localName, XmlConvert.ToString(value));
  2142. }
  2143. /// <summary>Writes the named element with content based on a 64-bit integer.</summary>
  2144. public static void WriteElement(this XmlWriter writer, string localName, long value)
  2145. {
  2146. if(writer == null) throw new ArgumentNullException();
  2147. writer.WriteElementString(localName, XmlConvert.ToString(value));
  2148. }
  2149. /// <summary>Writes the named element with content based on an 8-bit integer.</summary>
  2150. [CLSCompliant(false)]
  2151. public static void WriteElement(this XmlWriter writer, string localName, sbyte value)
  2152. {
  2153. if(writer == null) throw new ArgumentNullException();
  2154. writer.WriteElementString(localName, XmlConvert.ToString(value));
  2155. }
  2156. /// <summary>Writes the named element with content based on an 32-bit floating point value.</summary>
  2157. public static void WriteElement(this XmlWriter writer, string localName, float value)
  2158. {
  2159. if(writer == null) throw new ArgumentNullException();
  2160. writer.WriteElementString(localName, XmlConvert.ToString(value));
  2161. }
  2162. /// <summary>Writes the named element with content based on an <see cref="TimeSpan"/>.</summary>
  2163. public static void WriteElement(this XmlWriter writer, string localName, TimeSpan value)
  2164. {
  2165. if(writer == null) throw new ArgumentNullException();
  2166. writer.WriteElementString(localName, XmlConvert.ToString(value));
  2167. }
  2168. /// <summary>Writes the named element with content based on a 16-bit unsigned integer.</summary>
  2169. [CLSCompliant(false)]
  2170. public static void WriteElement(this XmlWriter writer, string localName, ushort value)
  2171. {
  2172. if(writer == null) throw new ArgumentNullException();
  2173. writer.WriteElementString(localName, XmlConvert.ToString(value));
  2174. }
  2175. /// <summary>Writes the named element with content based on a 32-bit unsigned integer.</summary>
  2176. [CLSCompliant(false)]
  2177. public static void WriteElement(this XmlWriter writer, string localName, uint value)
  2178. {
  2179. if(writer == null) throw new ArgumentNullException();
  2180. writer.WriteElementString(localName, XmlConvert.ToString(value));
  2181. }
  2182. /// <summary>Writes the named element with content based on a 64-bit unsigned integer.</summary>
  2183. [CLSCompliant(false)]
  2184. public static void WriteElement(this XmlWriter writer, string localName, ulong value)
  2185. {
  2186. if(writer == null) throw new ArgumentNullException();
  2187. writer.WriteElementString(localName, XmlConvert.ToString(value));
  2188. }
  2189. /// <summary>Writes an element with content based on an <see cref="XmlDuration"/> value.</summary>
  2190. public static void WriteElement(this XmlWriter writer, string localName, XmlDuration value)
  2191. {
  2192. if(writer == null) throw new ArgumentNullException();
  2193. writer.WriteElementString(localName, value.ToString());
  2194. }
  2195. /// <summary>Writes an element with the given name and value.</summary>
  2196. public static void WriteElementString(this XmlWriter writer, XmlQualifiedName qname, string value)
  2197. {
  2198. if(writer == null || qname == null) throw new ArgumentNullException();
  2199. writer.WriteElementString(qname.Name, qname.Namespace, value);
  2200. }
  2201. /// <summary>Writes an empty element with the given qualified name. Attributes cannot be added to the element.</summary>
  2202. public static void WriteEmptyElement(this XmlWriter writer, string localName)
  2203. {
  2204. if(writer == null) throw new ArgumentNullException();
  2205. writer.WriteStartElement(localName);
  2206. writer.WriteEndElement();
  2207. }
  2208. /// <summary>Writes an empty element with the given qualified name. Attributes cannot be added to the element.</summary>
  2209. public static void WriteEmptyElement(this XmlWriter writer, string localName, string ns)
  2210. {
  2211. if(writer == null) throw new ArgumentNullException();
  2212. writer.WriteStartElement(localName, ns);
  2213. writer.WriteEndElement();
  2214. }
  2215. /// <summary>Writes an empty element with the given qualified name. Attributes cannot be added to the element.</summary>
  2216. public static void WriteEmptyElement(this XmlWriter writer, string prefix, string localName, string ns)
  2217. {
  2218. if(writer == null) throw new ArgumentNullException();
  2219. writer.WriteStartElement(prefix, localName, ns);
  2220. writer.WriteEndElement();
  2221. }
  2222. /// <summary>Writes an empty element with the given qualified name. Attributes cannot be added to the element.</summary>
  2223. public static void WriteEmptyElement(this XmlWriter writer, XmlQualifiedName qname)
  2224. {
  2225. if(writer == null || qname == null) throw new ArgumentNullException();
  2226. writer.WriteStartElement(qname.Name, qname.Namespace);
  2227. writer.WriteEndElement();
  2228. }
  2229. /// <summary>Writes the specified qualified name, using an appropriate prefix for its namespace.</summary>
  2230. public static void WriteQualifiedName(this XmlWriter writer, XmlQualifiedName qname)
  2231. {
  2232. if(writer == null || qname == null) throw new ArgumentNullException();
  2233. writer.WriteQualifiedName(qname.Name, qname.Namespace);
  2234. }
  2235. /// <summary>Writes the start of an attribute with the specified qualified name.</summary>
  2236. public static void WriteStartAttribute(this XmlWriter writer, XmlQualifiedName qname)
  2237. {
  2238. if(writer == null || qname == null) throw new ArgumentNullException();
  2239. writer.WriteStartAttribute(qname.Name, qname.Namespace);
  2240. }
  2241. /// <summary>Writes a start tag with the specified qualified name.</summary>
  2242. public static void WriteStartElement(this XmlWriter writer, XmlQualifiedName qname)
  2243. {
  2244. if(writer == null || qname == null) throw new ArgumentNullException();
  2245. writer.WriteStartElement(qname.Name, qname.Namespace);
  2246. }
  2247. /// <summary>Writes an element with content based on the time portion of a <see cref="DateTime"/> value. The
  2248. /// <see cref="DateTimeKind"/> of the <see cref="DateTime"/> will be preserved.
  2249. /// </summary>
  2250. public static void WriteTimeElement(this XmlWriter writer, string localName, DateTime time)
  2251. {
  2252. writer.WriteTimeElement(localName, time, XmlDateTimeSerializationMode.RoundtripKind);
  2253. }
  2254. /// <summary>Writes an element with content based on the time portion of a <see cref="DateTime"/> value. The
  2255. /// <see cref="DateTimeKind"/> of the <see cref="DateTime"/> will be preserved.
  2256. /// </summary>
  2257. public static void WriteTimeElement(this XmlWriter writer, string localName, DateTime time, XmlDateTimeSerializationMode mode)
  2258. {
  2259. if(writer == null) throw new ArgumentNullException();
  2260. writer.WriteElementString(localName, XmlConvert.ToString(time, mode).Substring(11)); // strip off the date portion
  2261. }
  2262. }
  2263. #endregion
  2264. #region XmlUtility
  2265. /// <summary>Provides utilities for reading and writing XML.</summary>
  2266. public static class XmlUtility
  2267. {
  2268. /// <summary>Converts a string into an <c>xs:normalizedString</c> value.</summary>
  2269. public static string NormalizeString(string value)
  2270. {
  2271. return NormalizeString(value, false);
  2272. }
  2273. /// <summary>Converts a string into an <c>xs:TOKEN</c> value.</summary>
  2274. public static string NormalizeToken(string value)
  2275. {
  2276. return NormalizeString(value, true);
  2277. }
  2278. /// <summary>Parses a string containing a whitespace-separated list of items into an array of strings containing the substrings
  2279. /// corresponding to the individual items.
  2280. /// </summary>
  2281. public static string[] ParseList(string listValue)
  2282. {
  2283. if(listValue != null) listValue = listValue.Trim();
  2284. return string.IsNullOrEmpty(listValue) ? new string[0] : reListSplit.Split(listValue);
  2285. }
  2286. /// <summary>Parses a string containing a whitespace-separated list of items into an array containing the corresponding items,
  2287. /// using the given converter to convert an item's string representation into its value.
  2288. /// </summary>
  2289. public static T[] ParseList<T>(string listValue, Converter<string, T> converter)
  2290. {
  2291. if(converter == null) throw new ArgumentNullException("converter");
  2292. if(listValue != null) listValue = listValue.Trim();
  2293. if(string.IsNullOrEmpty(listValue))
  2294. {
  2295. return new T[0];
  2296. }
  2297. else
  2298. {
  2299. string[] bits = reListSplit.Split(listValue);
  2300. T[] values = new T[bits.Length];
  2301. for(int i=0; i<values.Length; i++) values[i] = converter(bits[i]);
  2302. return values;
  2303. }
  2304. }
  2305. /// <summary>Parses an <c>xs:date</c>, <c>xs:dateTime</c> value, preserving the time zone information it contains.</summary>
  2306. /// <param name="dateStr">The value, in <c>xs:date</c> or <c>xs:dateTime</c> format.</param>
  2307. /// <returns>Returns either a <see cref="DateTime"/> or <see cref="DateTimeOffset"/> value. If no time zone information is given, the
  2308. /// value will be a <see cref="DateTime"/> with a <see cref="DateTime.Kind"/> of <see cref="DateTimeKind.Unspecified"/>. If the UTC time
  2309. /// zone (<c>Z</c>) is given, the value will be a <see cref="DateTime"/> with a <see cref="DateTime.Kind"/> of
  2310. /// <see cref="DateTimeKind.Utc"/>. If any other time zone is given (including if the time zone is <c>+00:00</c> or <c>-00:00</c>), the
  2311. /// value will be a <see cref="DateTimeOffset"/> representing a local time in the given time zone.
  2312. /// </returns>
  2313. /// <exception cref="ArgumentNullException">Thrown if <paramref name="dateStr"/> is null.</exception>
  2314. /// <exception cref="FormatException">Thrown if <paramref name="dateStr"/> is not in the form required by the XML Schema specification.</exception>
  2315. public static object ParseDateTime(string dateStr)
  2316. {
  2317. if(dateStr == null) throw new ArgumentNullException();
  2318. object value;
  2319. if(!TryParseDateTime(dateStr, out value)) throw new FormatException();
  2320. return value;
  2321. }
  2322. /// <summary>Parses a qualified name (i.e. a name of the form <c>prefix:localName</c> or <c>namespaceUri:localName</c>) into an
  2323. /// <see cref="XmlQualifiedName"/>, using the given function to resolve prefixes. This method also accepts local names.
  2324. /// </summary>
  2325. public static XmlQualifiedName ParseQualifiedName(string qualifiedName, Func<string,string> prefixToNamespace)
  2326. {
  2327. if(prefixToNamespace == null) throw new ArgumentNullException();
  2328. if(string.IsNullOrEmpty(qualifiedName)) return XmlQualifiedName.Empty;
  2329. int start, length, colon = qualifiedName.LastIndexOf(':');
  2330. qualifiedName.Trim(out start, out length);
  2331. string prefix = colon == -1 ? "" : qualifiedName.Substring(start, colon-start), ns = prefixToNamespace(prefix);
  2332. string localName = colon == -1 ? qualifiedName : qualifiedName.Substring(colon+1, start+length-(colon+1));
  2333. return new XmlQualifiedName(localName, string.IsNullOrEmpty(ns) ? prefix : ns);
  2334. }
  2335. /// <summary>Tries to parse an <c>xs:boolean</c> value. Returns true if a boolean value was successfully parsed and false otherwise.</summary>
  2336. public static bool TryParse(string boolStr, out bool value)
  2337. {
  2338. if(!string.IsNullOrEmpty(boolStr))
  2339. {
  2340. int start, length;
  2341. boolStr.Trim(out start, out length);
  2342. char c = boolStr[start];
  2343. if(length == 1)
  2344. {
  2345. value = c == '1';
  2346. return value || c == '0';
  2347. }
  2348. else if(length == 4 && string.Compare(boolStr, start, "true", 0, 4, StringComparison.Ordinal) == 0)
  2349. {
  2350. value = true;
  2351. return true;
  2352. }
  2353. else if(length == 5 && string.Compare(boolStr, start, "false", 0, 5, StringComparison.Ordinal) == 0)
  2354. {
  2355. value = false;
  2356. return true;
  2357. }
  2358. }
  2359. value = false;
  2360. return false;
  2361. }
  2362. /// <summary>Tries to parse an <c>xs:date</c>, <c>xs:dateTime</c>, or <c>xs:datetimeoffset</c> value. <c>xs:datetimeoffset</c> values
  2363. /// will be returned in local time if the offset matches the local time offset, and will be converted into UTC otherwise.
  2364. /// </summary>
  2365. /// <returns>Returns true if the value was successfully parsed and false if not.</returns>
  2366. public static bool TryParse(string dateStr, out DateTime dateTime)
  2367. {
  2368. object value;
  2369. if(TryParseDateTime(dateStr, out value))
  2370. {
  2371. if(value is DateTime)
  2372. {
  2373. dateTime = (DateTime)value;
  2374. }
  2375. else
  2376. {
  2377. DateTimeOffset offset = (DateTimeOffset)value;
  2378. dateTime = offset.DateTime == offset.LocalDateTime ? offset.LocalDateTime : offset.UtcDateTime;
  2379. }
  2380. return true;
  2381. }
  2382. else
  2383. {
  2384. dateTime = new DateTime();
  2385. return false;
  2386. }
  2387. }
  2388. /// <summary>Tries to parse an <c>xsi:double</c> value.</summary>
  2389. public static bool TryParse(string floatStr, out double value)
  2390. {
  2391. if(!string.IsNullOrEmpty(floatStr))
  2392. {
  2393. if(InvariantCultureUtility.TryParse(floatStr, out value)) return true;
  2394. int start, length;
  2395. floatStr.Trim(out start, out length);
  2396. if(length == 3)
  2397. {
  2398. if(string.Compare(floatStr, start, "NaN", 0, 3, StringComparison.Ordinal) == 0)
  2399. {
  2400. value = double.NaN;
  2401. return true;
  2402. }
  2403. else if(string.Compare(floatStr, start, "INF", 0, 3, StringComparison.Ordinal) == 0)
  2404. {
  2405. value = double.PositiveInfinity;
  2406. return true;
  2407. }
  2408. }
  2409. else if(length == 4 && string.Compare(floatStr, start, "-INF", 0, 4, StringComparison.Ordinal) == 0)
  2410. {
  2411. value = double.NegativeInfinity;
  2412. return true;
  2413. }
  2414. }
  2415. value = 0;
  2416. return false;
  2417. }
  2418. /// <summary>Tries to parse an <c>xsi:float</c> value.</summary>
  2419. public static bool TryParse(string floatStr, out float value)
  2420. {
  2421. if(!string.IsNullOrEmpty(floatStr))
  2422. {
  2423. if(InvariantCultureUtility.TryParse(floatStr, out value)) return true;
  2424. int start, length;
  2425. floatStr.Trim(out start, out length);
  2426. if(length == 3)
  2427. {
  2428. if(string.Compare(floatStr, start, "NaN", 0, 3, StringComparison.Ordinal) == 0)
  2429. {
  2430. value = float.NaN;
  2431. return true;
  2432. }
  2433. else if(string.Compare(floatStr, start, "INF", 0, 3, StringComparison.Ordinal) == 0)
  2434. {
  2435. value = float.PositiveInfinity;
  2436. return true;
  2437. }
  2438. }
  2439. else if(length == 4 && string.Compare(floatStr, start, "-INF", 0, 4, StringComparison.Ordinal) == 0)
  2440. {
  2441. value = float.NegativeInfinity;
  2442. return true;
  2443. }
  2444. }
  2445. value = 0;
  2446. return false;
  2447. }
  2448. /// <summary>Tries to parse an <c>xsi:byte</c> value.</summary>
  2449. [CLSCompliant(false)]
  2450. public static bool TryParse(string str, out sbyte value)
  2451. {
  2452. return sbyte.TryParse(str, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out value);
  2453. }
  2454. /// <summary>Tries to parse an <c>xsi:decimal</c> value.</summary>
  2455. public static bool TryParse(string str, out decimal value)
  2456. {
  2457. const NumberStyles style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite |
  2458. NumberStyles.AllowTrailingWhite;
  2459. return decimal.TryParse(str, style, NumberFormatInfo.InvariantInfo, out value);
  2460. }
  2461. /// <summary>Tries to parse an <c>xsi:int</c> value.</summary>
  2462. public static bool TryParse(string str, out int value)
  2463. {
  2464. return int.TryParse(str, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out value);
  2465. }
  2466. /// <summary>Tries to parse an <c>xsi:long</c> value.</summary>
  2467. public static bool TryParse(string str, out long value)
  2468. {
  2469. return long.TryParse(str, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out value);
  2470. }
  2471. /// <summary>Tries to parse an <c>xsi:short</c> value.</summary>
  2472. public static bool TryParse(string str, out short value)
  2473. {
  2474. return short.TryParse(str, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out value);
  2475. }
  2476. /// <summary>Tries to parse an <c>xsi:unsignedByte</c> value.</summary>
  2477. public static bool TryParse(string str, out byte value)
  2478. {
  2479. return byte.TryParse(str, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out value);
  2480. }
  2481. /// <summary>Tries to parse an <c>xsi:unsignedInt</c> value.</summary>
  2482. [CLSCompliant(false)]
  2483. public static bool TryParse(string str, out uint value)
  2484. {
  2485. return uint.TryParse(str, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out value);
  2486. }
  2487. /// <summary>Tries to parse an <c>xsi:unsignedLong</c> value.</summary>
  2488. [CLSCompliant(false)]
  2489. public static bool TryParse(string str, out ulong value)
  2490. {
  2491. return ulong.TryParse(str, NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out value);
  2492. }
  2493. /// <summary>Tries to parse an <c>xsi:unsignedShort</c> value.</summary>
  2494. [CLSCompliant(false)]
  2495. public static bool TryParse(string str, out ushort value)
  2496. {
  2497. return ushort.TryParse(str, NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out value);
  2498. }
  2499. /// <summary>Tries to parse an <c>xs:date</c>, <c>xs:dateTime</c>, or <c>xs:datetimeoffset</c> value, preserving the time zone
  2500. /// information it contains.
  2501. /// </summary>
  2502. /// <param name="dateStr">The value, in <c>xs:date</c> or <c>xs:dateTime</c> format.</param>
  2503. /// <param name="value">A variable that receives either a <see cref="DateTime"/> or <see cref="DateTimeOffset"/> value. If no time zone
  2504. /// information is given, the value will be a <see cref="DateTime"/> with a <see cref="DateTime.Kind"/> of
  2505. /// <see cref="DateTimeKind.Unspecified"/>. If the UTC time zone (<c>Z</c>) is given, the value will be a <see cref="DateTime"/> with a
  2506. /// <see cref="DateTime.Kind"/> of <see cref="DateTimeKind.Utc"/>. If any other time zone is given (including if the time zone is
  2507. /// <c>+00:00</c> or <c>-00:00</c>), the value will be a <see cref="DateTimeOffset"/> representing a local time in the given time zone.
  2508. /// </param>
  2509. /// <returns>Returns true if the value was successfully parsed and false if not.</returns>
  2510. public static bool TryParseDateTime(string dateStr, out object value)
  2511. {
  2512. if(!string.IsNullOrEmpty(dateStr))
  2513. {
  2514. Match m = reDateTime.Match(dateStr);
  2515. if(m.Success)
  2516. {
  2517. int year, month, day, hour, minute;
  2518. double secs;
  2519. month = int.Parse(m.Groups["mo"].Value, CultureInfo.InvariantCulture);
  2520. day = int.Parse(m.Groups["d"].Value, CultureInfo.InvariantCulture);
  2521. if(m.Groups["h"].Success)
  2522. {
  2523. hour = int.Parse(m.Groups["h"].Value, CultureInfo.InvariantCulture);
  2524. minute = int.Parse(m.Groups["min"].Value, CultureInfo.InvariantCulture);
  2525. secs = double.Parse(m.Groups["s"].Value, CultureInfo.InvariantCulture);
  2526. }
  2527. else
  2528. {
  2529. hour = minute = 0;
  2530. secs = 0;
  2531. }
  2532. if(InvariantCultureUtility.TryParseExact(m.Groups["y"].Value, out year) && year > 0 && year <= 9999 &&
  2533. month > 0 && month <= 12 && day > 0 && day <= DateUtility.GetDaysInMonth(month, year) &&
  2534. (hour < 24 && minute < 60 && secs < 60 || hour == 24 && minute == 0 && secs == 0))
  2535. {
  2536. string tz = m.Groups["tz"].Value;
  2537. DateTimeKind kind = string.IsNullOrEmpty(tz) ? DateTimeKind.Unspecified :
  2538. tz.OrdinalEquals("Z") ? DateTimeKind.Utc : DateTimeKind.Local;
  2539. DateTime dateTime = new DateTime(year, month, day, hour == 24 ? 0 : hour, minute, 0, kind);
  2540. if(hour == 24) dateTime = dateTime.AddDays(1);
  2541. if(secs != 0) dateTime = dateTime.AddTicks((long)Math.Round(secs * TimeSpan.TicksPerSecond)); // .AddSeconds() has low precision
  2542. if(kind != DateTimeKind.Local)
  2543. {
  2544. value = dateTime;
  2545. }
  2546. else
  2547. {
  2548. TimeSpan offset = new TimeSpan(int.Parse(tz.Substring(1, 2), CultureInfo.InvariantCulture),
  2549. int.Parse(tz.Substring(4, 2), CultureInfo.InvariantCulture), 0);
  2550. value = new DateTimeOffset(dateTime.Ticks, tz[0] == '-' ? offset.Negate() : offset);
  2551. }
  2552. return true;
  2553. }
  2554. }
  2555. }
  2556. value = null;
  2557. return false;
  2558. }
  2559. /// <summary>Encodes the given text for safe insertion into XML elements and attributes. This
  2560. /// method is not suitable for encoding XML element and attribute names. (To encode names,
  2561. /// you should use <see cref="XmlConvert.EncodeName"/> or <see cref="XmlConvert.EncodeLocalName"/>.)
  2562. /// </summary>
  2563. public static string XmlEncode(string text)
  2564. {
  2565. return XmlEncode(text, true);
  2566. }
  2567. /// <summary>Encodes the given text for safe insertion into XML elements and, if <paramref name="isAttributeText"/> is true,
  2568. /// attributes. This method is not suitable for encoding XML element and attribute names, but only content. (To encode names,
  2569. /// you should use <see cref="XmlConvert.EncodeName"/> or <see cref="XmlConvert.EncodeLocalName"/>.)
  2570. /// </summary>
  2571. /// <param name="text">The text to encode. If null, null will be returned.</param>
  2572. /// <param name="isAttributeText">If true, additional characters (such as quotation marks, apostrophes, tabs, and newlines)
  2573. /// are encoded as well, allowing safe insertion into XML attributes. If false, the returned text may only be suitable for
  2574. /// insertion into elements.
  2575. /// </param>
  2576. public static string XmlEncode(string text, bool isAttributeText)
  2577. {
  2578. // if no characters need encoding, we'll just return the original string, so 'sb' will remain
  2579. // null until the character needs encoding.
  2580. StringBuilder sb = null;
  2581. if(text != null) // a null input string will be returned as null
  2582. {
  2583. for(int i=0; i<text.Length; i++)
  2584. {
  2585. string entity = null;
  2586. char c = text[i];
  2587. switch(c)
  2588. {
  2589. case '\t': case '\n': case '\r':
  2590. if(isAttributeText) entity = MakeHexEntity(c);
  2591. break;
  2592. case '"':
  2593. if(isAttributeText) entity = "&quot;";
  2594. break;
  2595. case '\'':
  2596. if(isAttributeText) entity = "&apos;";
  2597. break;
  2598. case '&':
  2599. entity = "&amp;";
  2600. break;
  2601. case '<':
  2602. entity = "&lt;";
  2603. break;
  2604. case '>':
  2605. entity = "&gt;";
  2606. break;
  2607. default:
  2608. // all non-printable or non-ASCII characters will be encoded, except for those above
  2609. if(c < 32 || c > 126) entity = MakeHexEntity(c);
  2610. break;
  2611. }
  2612. if(entity != null) // if the character needs to be encoded...
  2613. {
  2614. // initialize the string builder if we haven't already, with enough room for the text, plus some entities
  2615. if(sb == null) sb = new StringBuilder(text, 0, i, text.Length + 100);
  2616. sb.Append(entity); // then add the entity for the current character
  2617. }
  2618. else if(sb != null) // the character doesn't need encoding. only add it if a previous character has needed encoding...
  2619. {
  2620. sb.Append(c);
  2621. }
  2622. // TODO: we should perhaps try to deal with unicode surrogates, but i think we can ignore them for now
  2623. }
  2624. }
  2625. return sb != null ? sb.ToString() : text;
  2626. }
  2627. static bool IsWhitespace(char c)
  2628. {
  2629. return c == ' ' || c == '\t' || c == '\n' || c == '\r';
  2630. }
  2631. /// <summary>Creates and returns an XML entity containing the character's hex code.</summary>
  2632. static string MakeHexEntity(char c)
  2633. {
  2634. return "&#x" + ((int)c).ToString("X", CultureInfo.InvariantCulture) + ";";
  2635. }
  2636. /// <summary>Converts a string to a <c>xs:normalizedString</c> or <c>xs:TOKEN</c> value.</summary>
  2637. static string NormalizeString(string value, bool trim)
  2638. {
  2639. if(value != null)
  2640. {
  2641. bool previouslySpace = false;
  2642. int start = 0, end = value.Length;
  2643. if(trim && Trim(value, out start, out end)) end += start;
  2644. for(int i=start; i<end; i++)
  2645. {
  2646. char c = value[i];
  2647. bool encode = false;
  2648. if(c == ' ')
  2649. {
  2650. if(previouslySpace) encode = true;
  2651. else previouslySpace = true;
  2652. }
  2653. else if(c == '\t' || c == '\n' || c == '\r')
  2654. {
  2655. encode = true;
  2656. }
  2657. else
  2658. {
  2659. previouslySpace = false;
  2660. }
  2661. if(encode)
  2662. {
  2663. StringBuilder sb = new StringBuilder(value.Length);
  2664. sb.Append(value, start, i-start);
  2665. while(true)
  2666. {
  2667. if(c == '\t' || c == '\n' || c == '\r') c = ' ';
  2668. if(c == ' ')
  2669. {
  2670. if(!previouslySpace)
  2671. {
  2672. sb.Append(' ');
  2673. previouslySpace = true;
  2674. }
  2675. }
  2676. else
  2677. {
  2678. sb.Append(c);
  2679. previouslySpace = false;
  2680. }
  2681. if(++i == end) break;
  2682. c = value[i];
  2683. }
  2684. return sb.ToString();
  2685. }
  2686. }
  2687. if(start != 0 || end != value.Length) value = value.Substring(start, end-start);
  2688. }
  2689. return value;
  2690. }
  2691. static bool Trim(string str, out int start, out int length)
  2692. {
  2693. int i = 0, j = str.Length - 1;
  2694. while(i < str.Length && IsWhitespace(str[i])) i++;
  2695. while(j > i && IsWhitespace(str[j])) j--;
  2696. if(j < i)
  2697. {
  2698. start = 0;
  2699. length = 0;
  2700. return str.Length != 0;
  2701. }
  2702. else
  2703. {
  2704. start = i;
  2705. length = j - i + 1;
  2706. return i != 0 || j != str.Length - 1;
  2707. }
  2708. }
  2709. static readonly Regex reDateTime =
  2710. new Regex(@"^\s*(?<y>-?[0-9]{4,})-(?<mo>[0-9]{2})-(?<d>[0-9]{2})(?:T(?<h>[0-9]{2}):(?<min>[0-9]{2}):(?<s>[0-9]{2}(?:\.[0-9]+)?)(?<tz>Z|[+\-][0-9]{2}:[0-9]{2})?)?\s*$",
  2711. RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Singleline);
  2712. static readonly Regex reListSplit = new Regex(@"\s+", RegexOptions.Singleline);
  2713. }
  2714. #endregion
  2715. } // namespace AdamMil.Utilities