xmlutils.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # -*- coding: utf-8 -*-
  2. # copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
  3. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
  4. #
  5. # This file is part of logilab-common.
  6. #
  7. # logilab-common is free software: you can redistribute it and/or modify it under
  8. # the terms of the GNU Lesser General Public License as published by the Free
  9. # Software Foundation, either version 2.1 of the License, or (at your option) any
  10. # later version.
  11. #
  12. # logilab-common is distributed in the hope that it will be useful, but WITHOUT
  13. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  14. # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  15. # details.
  16. #
  17. # You should have received a copy of the GNU Lesser General Public License along
  18. # with logilab-common. If not, see <http://www.gnu.org/licenses/>.
  19. """XML utilities.
  20. This module contains useful functions for parsing and using XML data. For the
  21. moment, there is only one function that can parse the data inside a processing
  22. instruction and return a Python dictionary.
  23. """
  24. __docformat__ = "restructuredtext en"
  25. import re
  26. RE_DOUBLE_QUOTE = re.compile('([\w\-\.]+)="([^"]+)"')
  27. RE_SIMPLE_QUOTE = re.compile("([\w\-\.]+)='([^']+)'")
  28. def parse_pi_data(pi_data):
  29. """
  30. Utility function that parses the data contained in an XML
  31. processing instruction and returns a dictionary of keywords and their
  32. associated values (most of the time, the processing instructions contain
  33. data like ``keyword="value"``, if a keyword is not associated to a value,
  34. for example ``keyword``, it will be associated to ``None``).
  35. :param pi_data: data contained in an XML processing instruction.
  36. :type pi_data: unicode
  37. :returns: Dictionary of the keywords (Unicode strings) associated to
  38. their values (Unicode strings) as they were defined in the
  39. data.
  40. :rtype: dict
  41. """
  42. results = {}
  43. for elt in pi_data.split():
  44. if RE_DOUBLE_QUOTE.match(elt):
  45. kwd, val = RE_DOUBLE_QUOTE.match(elt).groups()
  46. elif RE_SIMPLE_QUOTE.match(elt):
  47. kwd, val = RE_SIMPLE_QUOTE.match(elt).groups()
  48. else:
  49. kwd, val = elt, None
  50. results[kwd] = val
  51. return results