xpath.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # -*- coding: utf-8 -*-
  2. """
  3. sleekxmpp.xmlstream.matcher.xpath
  4. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  5. Part of SleekXMPP: The Sleek XMPP Library
  6. :copyright: (c) 2011 Nathanael C. Fritz
  7. :license: MIT, see LICENSE for more details
  8. """
  9. from sleekxmpp.xmlstream.stanzabase import ET, fix_ns
  10. from sleekxmpp.xmlstream.matcher.base import MatcherBase
  11. class MatchXPath(MatcherBase):
  12. """
  13. The XPath matcher selects stanzas whose XML contents matches a given
  14. XPath expression.
  15. .. warning::
  16. Using this matcher may not produce expected behavior when using
  17. attribute selectors. For Python 2.6 and 3.1, the ElementTree
  18. :meth:`~xml.etree.ElementTree.Element.find()` method does
  19. not support the use of attribute selectors. If you need to
  20. support Python 2.6 or 3.1, it might be more useful to use a
  21. :class:`~sleekxmpp.xmlstream.matcher.stanzapath.StanzaPath` matcher.
  22. If the value of :data:`IGNORE_NS` is set to ``True``, then XPath
  23. expressions will be matched without using namespaces.
  24. """
  25. def __init__(self, criteria):
  26. self._criteria = fix_ns(criteria)
  27. def match(self, xml):
  28. """
  29. Compare a stanza's XML contents to an XPath expression.
  30. If the value of :data:`IGNORE_NS` is set to ``True``, then XPath
  31. expressions will be matched without using namespaces.
  32. .. warning::
  33. In Python 2.6 and 3.1 the ElementTree
  34. :meth:`~xml.etree.ElementTree.Element.find()` method does not
  35. support attribute selectors in the XPath expression.
  36. :param xml: The :class:`~sleekxmpp.xmlstream.stanzabase.ElementBase`
  37. stanza to compare against.
  38. """
  39. if hasattr(xml, 'xml'):
  40. xml = xml.xml
  41. x = ET.Element('x')
  42. x.append(xml)
  43. return x.find(self._criteria) is not None