Debian Codegraph @

petl/io/xml.py

raw
1 # -*- coding: utf-8 -*-
2 from __future__ import absolute_import, print_function, division
3
4
5 # standard library dependencies
6 try:
7 # prefer lxml as it supports XPath
8 from lxml import etree
9 except ImportError:
10 import xml.etree.ElementTree as etree
11
12 from operator import attrgetter
13 import itertools
14 from petl.compat import string_types, text_type
15
16
17 # internal dependencies
18 from petl.util.base import Table, fieldnames, iterpeek
19 from petl.io.sources import read_source_from_arg
20 from petl.io.text import totext
21
22
23 def fromxml(source, *args, **kwargs):
24 """
25 Extract data from an XML file. E.g.::
26
27 >>> import petl as etl
28 >>> # setup a file to demonstrate with
29 ... d = '''<table>
30 ... <tr>
31 ... <td>foo</td><td>bar</td>
32 ... </tr>
33 ... <tr>
34 ... <td>a</td><td>1</td>
35 ... </tr>
36 ... <tr>
37 ... <td>b</td><td>2</td>
38 ... </tr>
39 ... <tr>
40 ... <td>c</td><td>2</td>
41 ... </tr>
42 ... </table>'''
43 >>> with open('example.file1.xml', 'w') as f:
44 ... f.write(d)
45 ...
46 212
47 >>> table1 = etl.fromxml('example.file1.xml', 'tr', 'td')
48 >>> table1
49 +-----+-----+
50 | foo | bar |
51 +=====+=====+
52 | 'a' | '1' |
53 +-----+-----+
54 | 'b' | '2' |
55 +-----+-----+
56 | 'c' | '2' |
57 +-----+-----+
58
59
60 If the data values are stored in an attribute, provide the attribute
61 name as an extra positional argument::
62
63 >>> d = '''<table>
64 ... <tr>
65 ... <td v='foo'/><td v='bar'/>
66 ... </tr>
67 ... <tr>
68 ... <td v='a'/><td v='1'/>
69 ... </tr>
70 ... <tr>
71 ... <td v='b'/><td v='2'/>
72 ... </tr>
73 ... <tr>
74 ... <td v='c'/><td v='2'/>
75 ... </tr>
76 ... </table>'''
77 >>> with open('example.file2.xml', 'w') as f:
78 ... f.write(d)
79 ...
80 220
81 >>> table2 = etl.fromxml('example.file2.xml', 'tr', 'td', 'v')
82 >>> table2
83 +-----+-----+
84 | foo | bar |
85 +=====+=====+
86 | 'a' | '1' |
87 +-----+-----+
88 | 'b' | '2' |
89 +-----+-----+
90 | 'c' | '2' |
91 +-----+-----+
92
93 Data values can also be extracted by providing a mapping of field
94 names to element paths::
95
96 >>> d = '''<table>
97 ... <row>
98 ... <foo>a</foo><baz><bar v='1'/><bar v='3'/></baz>
99 ... </row>
100 ... <row>
101 ... <foo>b</foo><baz><bar v='2'/></baz>
102 ... </row>
103 ... <row>
104 ... <foo>c</foo><baz><bar v='2'/></baz>
105 ... </row>
106 ... </table>'''
107 >>> with open('example.file3.xml', 'w') as f:
108 ... f.write(d)
109 ...
110 223
111 >>> table3 = etl.fromxml('example.file3.xml', 'row',
112 ... {'foo': 'foo', 'bar': ('baz/bar', 'v')})
113 >>> table3
114 +------------+-----+
115 | bar | foo |
116 +============+=====+
117 | ('1', '3') | 'a' |
118 +------------+-----+
119 | '2' | 'b' |
120 +------------+-----+
121 | '2' | 'c' |
122 +------------+-----+
123
124 If `lxml <http://lxml.de/>`_ is installed, full XPath expressions can be
125 used.
126
127 Note that the implementation is currently **not** streaming, i.e.,
128 the whole document is loaded into memory.
129
130 If multiple elements match a given field, all values are reported as a
131 tuple.
132
133 If there is more than one element name used for row values, a tuple
134 or list of paths can be provided, e.g.,
135 ``fromxml('example.file.html', './/tr', ('th', 'td'))``.
136
137 Optionally a custom parser can be provided, e.g.::
138
139 >>> from lxml import etree # doctest: +SKIP
140 ... my_parser = etree.XMLParser(resolve_entities=False) # doctest: +SKIP
141 ... table4 = etl.fromxml('example.file1.xml', 'tr', 'td', parser=my_parser) # doctest: +SKIP
142
143 """
144
145 source = read_source_from_arg(source)
146 return XmlView(source, *args, **kwargs)
147
148
149 class XmlView(Table):
150
151 def __init__(self, source, *args, **kwargs):
152 self.source = source
153 self.args = args
154 if len(args) == 2 and isinstance(args[1], (string_types, tuple, list)):
155 self.rmatch = args[0]
156 self.vmatch = args[1]
157 self.vdict = None
158 self.attr = None
159 elif len(args) == 2 and isinstance(args[1], dict):
160 self.rmatch = args[0]
161 self.vmatch = None
162 self.vdict = args[1]
163 self.attr = None
164 elif len(args) == 3:
165 self.rmatch = args[0]
166 self.vmatch = args[1]
167 self.vdict = None
168 self.attr = args[2]
169 else:
170 assert False, 'bad parameters'
171 self.missing = kwargs.get('missing', None)
172 self.user_parser = kwargs.get('parser', None)
173
174 def __iter__(self):
175 vmatch = self.vmatch
176 vdict = self.vdict
177
178 with self.source.open('rb') as xmlf:
179 parser2 = _create_xml_parser(self.user_parser)
180 tree = etree.parse(xmlf, parser=parser2)
181 if not hasattr(tree, 'iterfind'):
182 # Python 2.6 compatibility
183 tree.iterfind = tree.findall
184
185 if vmatch is not None:
186 # simple case, all value paths are the same
187 for rowelm in tree.iterfind(self.rmatch):
188 if self.attr is None:
189 getv = attrgetter('text')
190 else:
191 getv = lambda e: e.get(self.attr)
192 if isinstance(vmatch, string_types):
193 # match only one path
194 velms = rowelm.findall(vmatch)
195 else:
196 # match multiple paths
197 velms = itertools.chain(*[rowelm.findall(enm)
198 for enm in vmatch])
199 yield tuple(getv(velm)
200 for velm in velms)
201
202 else:
203 # difficult case, deal with different paths for each field
204
205 # determine output header
206 flds = tuple(sorted(map(text_type, vdict.keys())))
207 yield flds
208
209 # setup value getters
210 vmatches = dict()
211 vgetters = dict()
212 for f in flds:
213 vmatch = self.vdict[f]
214 if isinstance(vmatch, string_types):
215 # match element path
216 vmatches[f] = vmatch
217 vgetters[f] = element_text_getter(self.missing)
218 else:
219 # match element path and attribute name
220 vmatches[f] = vmatch[0]
221 attr = vmatch[1]
222 vgetters[f] = attribute_text_getter(attr, self.missing)
223
224 # determine data rows
225 for rowelm in tree.iterfind(self.rmatch):
226 yield tuple(vgetters[f](rowelm.findall(vmatches[f]))
227 for f in flds)
228
229
230 def _create_xml_parser(user_parser):
231 if user_parser is not None:
232 return user_parser
233 try:
234 # Default lxml parser.
235 # This will throw an error if parser is not set and lxml could not be imported
236 # because Python's built XML parser doesn't like the `resolve_entities` kwarg.
237 # return etree.XMLParser(resolve_entities=False)
238 return etree.XMLParser(resolve_entities=False)
239 except TypeError:
240 # lxml not available
241 return None
242
243
244 def element_text_getter(missing):
245 def _get(v):
246 if len(v) > 1:
247 return tuple(e.text for e in v)
248 elif len(v) == 1:
249 return v[0].text
250 else:
251 return missing
252 return _get
253
254
255 def attribute_text_getter(attr, missing):
256 def _get(v):
257 if len(v) > 1:
258 return tuple(e.get(attr) for e in v)
259 elif len(v) == 1:
260 return v[0].get(attr)
261 else:
262 return missing
263 return _get
264
265
266 def toxml(table, target=None,
267 root=None, head=None, rows=None, prologue=None, epilogue=None,
268 style='tag', encoding='utf-8'):
269 """
270 Write the table into a new xml file according to elements defined in the
271 function arguments.
272
273 The `root`, `head` and `rows` (string, optional) arguments define the tags
274 and the nesting of the xml file. Each one defines xml elements with tags
275 separated by slashes (`/`) like in `root/level/tag`. They can have a
276 arbitrary number of tags that will reflect in more nesting levels for the
277 header or record/row written in the xml file.
278
279 For details on tag naming and nesting rules check xml `specification`_ or
280 xml `references`_.
281
282 The `rows` argument define the elements for each row of data to be written
283 in the xml file. When specified, it must have at least 2 tags for defining
284 the tags for `row/column`. Additional tags will add nesting enclosing all
285 records/rows/lines.
286
287 The `head` argument is similar to the rows, but aplies only to one line/row
288 of header with fieldnames. When specified, it must have at least 2 tags for
289 `fields/name` and the remaining will increase nesting.
290
291 The `root` argument defines the elements enclosing `head` and `rows` and is
292 required when using `head` for specifying valid xml documents.
293
294 When none of this arguments are specified, they will default to tags that
295 generate output similar to a html table:
296 `root='table', head='there/tr/td', rows='tbody/tr/td'`.
297
298 The `prologue` argument (string, optional) could be a snippet of valid xml
299 that will be inserted before other elements in the xml. It can optionally
300 specify the `XML Prolog` of the file.
301
302 The `epilogue` argument (string, optional) could be a snippet of valid xml
303 that will be inserted after all other xml elements except the root closing
304 tag. It must specify a closing tag if the `root` argument is not specified.
305
306 The `style` argument select the format of the elements in the xml file. It
307 can be `tag` (default), `name`, `attribute` or a custom string to format
308 each row via
309 `str.format <http://docs.python.org/library/stdtypes.html#str.format>`_.
310
311 Example usage for writing files::
312
313 >>> import petl as etl
314 >>> table1 = [['foo', 'bar'],
315 ... ['a', 1],
316 ... ['b', 2]]
317 >>> etl.toxml(table1, 'example.file4.xml')
318 >>> # see what we did is similar a html table:
319 >>> print(open('example.file4.xml').read())
320 <?xml version="1.0" encoding="UTF-8"?>
321 <table><thead>
322 <tr><th>foo</th><th>bar</th></tr>
323 </thead><tbody>
324 <tr><td>a</td><td>1</td></tr>
325 <tr><td>b</td><td>2</td></tr>
326 </tbody></table>
327 >>> # define the nesting in xml file:
328 >>> etl.toxml(table1, 'example.file5.xml', rows='plan/line/cell')
329 >>> print(open('example.file5.xml').read())
330 <?xml version="1.0" encoding="UTF-8"?>
331 <plan>
332 <line><cell>a</cell><cell>1</cell></line>
333 <line><cell>b</cell><cell>2</cell></line>
334 </plan>
335 >>> # choose other style:
336 >>> etl.toxml(table1, 'example.file6.xml', rows='row/col', style='attribute')
337 >>> print(open('example.file6.xml').read())
338 <?xml version="1.0" encoding="UTF-8"?>
339 <row>
340 <col foo="a" bar="1" />
341 <col foo="b" bar="2" />
342 </row>
343 >>> etl.toxml(table1, 'example.file6.xml', rows='row/col', style='name')
344 >>> print(open('example.file6.xml').read())
345 <?xml version="1.0" encoding="UTF-8"?>
346 <row>
347 <col><foo>a</foo><bar>1</bar></col>
348 <col><foo>b</foo><bar>2</bar></col>
349 </row>
350
351 The `toxml()` function is just a wrapper over :func:`petl.io.text.totext`.
352 For advanced cases use a template with `totext()` for generating xml files.
353
354 .. versionadded:: 1.7.0
355
356 .. _specification: https://www.w3.org/TR/xml/
357 .. _references: https://www.w3schools.com/xml/xml_syntax.asp
358
359 """
360 if not root and not head and not rows:
361 root = 'table'
362 head = 'thead/tr/th'
363 rows = 'tbody/tr/td'
364
365 sample, table2 = iterpeek(table, 2)
366 props = fieldnames(sample)
367
368 top = _build_xml_header(style, props, root, head, rows, prologue, encoding)
369 template = _build_cols(style, props, rows, True)
370 bottom = _build_xml_footer(style, epilogue, rows, root)
371
372 totext(table2, source=target, encoding=encoding, errors='strict',
373 template=template, prologue=top, epilogue=bottom)
374
375
376 def _build_xml_header(style, props, root, head, rows, prologue, encoding):
377 tab = _build_nesting(root, False, None) if root else ''
378 nested = -1 if style in ('attribute', 'name') else -2
379 if head:
380 th1 = _build_nesting(head, False, nested)
381 col = _build_cols(style, props, head, False)
382 th2 = _build_nesting(head, True, nested)
383 thd = '{0}\n{1}{2}'.format(th1, col, th2)
384 else:
385 thd = ''
386 tbd = _build_nesting(rows, False, nested)
387 if prologue and prologue.startswith('<?xml'):
388 thb = '{0}{1}{2}\n'.format(tab, thd, tbd)
389 return prologue + thb
390 enc = encoding.upper() if encoding else 'UTF-8'
391 xml = '<?xml version="1.0" encoding="%s"?>' % enc
392 pre = prologue + '\n' if prologue and not root else ''
393 pos = '\n' + prologue if prologue and root else ''
394 res = '{0}\n{1}{2}{3}{4}{5}\n'.format(xml, pre, tab, thd, tbd, pos)
395 return res
396
397
398 def _build_xml_footer(style, epilogue, rows, root):
399 nested = -1 if style in ('attribute', 'name') else -2
400 tbd = _build_nesting(rows, True, nested)
401 tab = _build_nesting(root, True, 0)
402 pre = epilogue + '\n' if epilogue and root else ''
403 pos = '\n' + epilogue if epilogue and not root else ''
404 return pre + tbd + tab + pos
405
406
407 def _build_nesting(path, closing, index):
408 if not path:
409 return ''
410 fmt = '</%s>' if closing else '<%s>'
411 if '/' not in path:
412 return fmt % path
413 parts = path.split('/')
414 elements = parts[0:index] if index else parts
415 if closing:
416 elements.reverse()
417 tags = [fmt % e for e in elements]
418 return ''.join(tags)
419
420
421 def _build_cols(style, props, path, is_value):
422 is_header = not is_value
423 if style == 'tag' or is_header:
424 return _build_cols_inline(props, path, is_value, True)
425 if style == 'name':
426 return _build_cols_inline(props, path, is_value, False)
427 if style == 'attribute':
428 return _build_cols_attribs(props, path)
429 return style # custom
430
431
432 def _build_cols_inline(props, path, is_value, use_tag):
433 parts = path.split('/')
434 if use_tag:
435 if len(parts) < 2:
436 raise ValueError("Tag not in format 'row/col': %s" % path)
437 col = parts[-1]
438 row = parts[-2:-1][0]
439 else:
440 col = '{0}'
441 row = parts[-1]
442 fld = '{{{0}}}' if is_value else '{0}'
443 fmt = '<{0}>{1}</{0}>'.format(col, fld)
444 cols = [fmt.format(e) for e in props]
445 tags = ''.join(cols)
446 res = ' <{0}>{1}</{0}>\n'.format(row, tags)
447 return res
448
449
450 def _build_cols_attribs(props, path):
451 parts = path.split('/')
452 row = parts[-1]
453 fmt = '{0}="{{{0}}}"'
454 cols = [fmt.format(e) for e in props]
455 atts = ' '.join(cols)
456 res = ' <{0} {1} />\n'.format(row, atts)
457 return res