Package logilab :: Package common :: Module xmlutils
[frames] | no frames]

Source Code for Module logilab.common.xmlutils

 1  # -*- coding: utf-8 -*- 
 2  """XML utilities. 
 3   
 4  This module contains useful functions for parsing and using XML data. For the 
 5  moment, there is only one function that can parse the data inside a processing 
 6  instruction and return a Python dictionary. 
 7   
 8  :copyright: 2009 LOGILAB S.A. (Paris, FRANCE), all rights reserved. 
 9  :contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr 
10  :license: General Public License version 2 - http://www.gnu.org/licenses 
11  """ 
12  __docformat__ = "restructuredtext en" 
13   
14  import re 
15   
16  RE_DOUBLE_QUOTE = re.compile('([\w\-\.]+)="([^"]+)"') 
17  RE_SIMPLE_QUOTE = re.compile("([\w\-\.]+)='([^']+)'") 
18   
19 -def parse_pi_data(pi_data):
20 """ 21 Utility function that parses the data contained in an XML 22 processing instruction and returns a dictionary of keywords and their 23 associated values (most of the time, the processing instructions contain 24 data like ``keyword="value"``, if a keyword is not associated to a value, 25 for example ``keyword``, it will be associated to ``None``). 26 27 :param pi_data: data contained in an XML processing instruction. 28 :type pi_data: unicode 29 30 :returns: Dictionary of the keywords (Unicode strings) associated to 31 their values (Unicode strings) as they were defined in the 32 data. 33 :rtype: dict 34 """ 35 results = {} 36 for elt in pi_data.split(): 37 if RE_DOUBLE_QUOTE.match(elt): 38 kwd, val = RE_DOUBLE_QUOTE.match(elt).groups() 39 elif RE_SIMPLE_QUOTE.match(elt): 40 kwd, val = RE_SIMPLE_QUOTE.match(elt).groups() 41 else: 42 kwd, val = elt, None 43 results[kwd] = val 44 return results
45