XPathBinder.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. //
  2. // System.Web.UI.XPathBinder
  3. //
  4. // Authors:
  5. // Ben Maurer ([email protected])
  6. //
  7. // (C) 2003 Ben Maurer
  8. //
  9. #if NET_1_2
  10. using System.Collections;
  11. using System.Collections.Specialized;
  12. using System.Text;
  13. using System.Xml.XPath;
  14. using System.Xml;
  15. namespace System.Web.UI {
  16. public sealed class XPathBinder {
  17. private XPathBinder ()
  18. {
  19. }
  20. public static object Eval (object container, string xpath)
  21. {
  22. if (xpath == null || xpath.Length == 0)
  23. throw new ArgumentNullException ("xpath");
  24. IXPathNavigable factory = container as IXPathNavigable;
  25. if (factory == null)
  26. throw new ArgumentException ("container");
  27. object result = factory.CreateNavigator ().Evaluate (xpath);
  28. XPathNodeIterator itr = result as XPathNodeIterator;
  29. if (itr != null) {
  30. if (itr.MoveNext())
  31. return itr.Current.Value;
  32. else
  33. return null;
  34. }
  35. return result;
  36. }
  37. public static string Eval (object container, string xpath, string format)
  38. {
  39. object result = Eval (container, xpath);
  40. if (result == null)
  41. return String.Empty;
  42. if (format == null || format.Length == 0)
  43. return result.ToString ();
  44. return String.Format (format, result);
  45. }
  46. public static IEnumerable Select (object container, string xpath)
  47. {
  48. if (xpath == null || xpath.Length == 0)
  49. throw new ArgumentNullException ("xpath");
  50. IXPathNavigable factory = container as IXPathNavigable;
  51. if (factory == null)
  52. throw new ArgumentException ("container");
  53. XPathNodeIterator itr = factory.CreateNavigator ().Select (xpath);
  54. ArrayList ret = new ArrayList ();
  55. while (itr.MoveNext ()) {
  56. IHasXmlNode nodeAccessor = itr.Current as IHasXmlNode;
  57. if (nodeAccessor == null)
  58. throw new InvalidOperationException ();
  59. ret.Add (nodeAccessor.GetNode ());
  60. }
  61. return ret;
  62. }
  63. }
  64. }
  65. #endif