Debian Codegraph @

lib-python/3/xml/etree/ElementTree.py

raw symbols SCIP
1 """Lightweight XML support for Python.
2
3 XML is an inherently hierarchical data format, and the most natural way to
4 represent it is with a tree. This module has two classes for this purpose:
5
6 1. ElementTree represents the whole XML document as a tree and
7
8 2. Element represents a single node in this tree.
9
10 Interactions with the whole document (reading and writing to/from files) are
11 usually done on the ElementTree level. Interactions with a single XML element
12 and its sub-elements are done on the Element level.
13
14 Element is a flexible container object designed to store hierarchical data
15 structures in memory. It can be described as a cross between a list and a
16 dictionary. Each Element has a number of properties associated with it:
17
18 'tag' - a string containing the element's name.
19
20 'attributes' - a Python dictionary storing the element's attributes.
21
22 'text' - a string containing the element's text content.
23
24 'tail' - an optional string containing text after the element's end tag.
25
26 And a number of child elements stored in a Python sequence.
27
28 To create an element instance, use the Element constructor,
29 or the SubElement factory function.
30
31 You can also use the ElementTree class to wrap an element structure
32 and convert it to and from XML.
33
34 """
35
36 #---------------------------------------------------------------------
37 # Licensed to PSF under a Contributor Agreement.
38 # See https://www.python.org/psf/license for licensing details.
39 #
40 # ElementTree
41 # Copyright (c) 1999-2008 by Fredrik Lundh. All rights reserved.
42 #
43 # [email protected]
44 # http://www.pythonware.com
45 # --------------------------------------------------------------------
46 # The ElementTree toolkit is
47 #
48 # Copyright (c) 1999-2008 by Fredrik Lundh
49 #
50 # By obtaining, using, and/or copying this software and/or its
51 # associated documentation, you agree that you have read, understood,
52 # and will comply with the following terms and conditions:
53 #
54 # Permission to use, copy, modify, and distribute this software and
55 # its associated documentation for any purpose and without fee is
56 # hereby granted, provided that the above copyright notice appears in
57 # all copies, and that both that copyright notice and this permission
58 # notice appear in supporting documentation, and that the name of
59 # Secret Labs AB or the author not be used in advertising or publicity
60 # pertaining to distribution of the software without specific, written
61 # prior permission.
62 #
63 # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
64 # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
65 # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
66 # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
67 # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
68 # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
69 # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
70 # OF THIS SOFTWARE.
71 # --------------------------------------------------------------------
72
73 __all__ = [
74 # public symbols
75 "Comment",
76 "dump",
77 "Element", "ElementTree",
78 "fromstring", "fromstringlist",
79 "indent", "iselement", "iterparse",
80 "parse", "ParseError",
81 "PI", "ProcessingInstruction",
82 "QName",
83 "SubElement",
84 "tostring", "tostringlist",
85 "TreeBuilder",
86 "VERSION",
87 "XML", "XMLID",
88 "XMLParser", "XMLPullParser",
89 "register_namespace",
90 "canonicalize", "C14NWriterTarget",
91 ]
92
93 VERSION = "1.3.0"
94
95 import sys
96 import re
97 import warnings
98 import io
99 import collections
100 import collections.abc
101 import contextlib
102 import weakref
103
104 from . import ElementPath
105
106
107 class ParseError(SyntaxError):
108 """An error when parsing an XML document.
109
110 In addition to its exception value, a ParseError contains
111 two extra attributes:
112 'code' - the specific exception code
113 'position' - the line and column of the error
114
115 """
116 pass
117
118 # --------------------------------------------------------------------
119
120
121 def iselement(element):
122 """Return True if *element* appears to be an Element."""
123 return hasattr(element, 'tag')
124
125
126 class Element:
127 """An XML element.
128
129 This class is the reference implementation of the Element interface.
130
131 An element's length is its number of subelements. That means if you
132 want to check if an element is truly empty, you should check BOTH
133 its length AND its text attribute.
134
135 The element tag, attribute names, and attribute values can be either
136 bytes or strings.
137
138 *tag* is the element name. *attrib* is an optional dictionary containing
139 element attributes. *extra* are additional element attributes given as
140 keyword arguments.
141
142 Example form:
143 <tag attrib>text<child/>...</tag>tail
144
145 """
146
147 tag = None
148 """The element's name."""
149
150 attrib = None
151 """Dictionary of the element's attributes."""
152
153 text = None
154 """
155 Text before first subelement. This is either a string or the value None.
156 Note that if there is no text, this attribute may be either
157 None or the empty string, depending on the parser.
158
159 """
160
161 tail = None
162 """
163 Text after this element's end tag, but before the next sibling element's
164 start tag. This is either a string or the value None. Note that if there
165 was no text, this attribute may be either None or an empty string,
166 depending on the parser.
167
168 """
169
170 def __init__(self, tag, attrib={}, **extra):
171 if not isinstance(attrib, dict):
172 raise TypeError("attrib must be dict, not %s" % (
173 attrib.__class__.__name__,))
174 self.tag = tag
175 self.attrib = {**attrib, **extra}
176 self._children = []
177
178 def __repr__(self):
179 return "<%s %r at %#x>" % (self.__class__.__name__, self.tag, id(self))
180
181 def makeelement(self, tag, attrib):
182 """Create a new element with the same type.
183
184 *tag* is a string containing the element name.
185 *attrib* is a dictionary containing the element attributes.
186
187 Do not call this method, use the SubElement factory function instead.
188
189 """
190 return self.__class__(tag, attrib)
191
192 def copy(self):
193 """Return copy of current element.
194
195 This creates a shallow copy. Subelements will be shared with the
196 original tree.
197
198 """
199 warnings.warn(
200 "elem.copy() is deprecated. Use copy.copy(elem) instead.",
201 DeprecationWarning
202 )
203 return self.__copy__()
204
205 def __copy__(self):
206 elem = self.makeelement(self.tag, self.attrib)
207 elem.text = self.text
208 elem.tail = self.tail
209 elem[:] = self
210 return elem
211
212 def __len__(self):
213 return len(self._children)
214
215 def __bool__(self):
216 warnings.warn(
217 "The behavior of this method will change in future versions. "
218 "Use specific 'len(elem)' or 'elem is not None' test instead.",
219 FutureWarning, stacklevel=2
220 )
221 return len(self._children) != 0 # emulate old behaviour, for now
222
223 def __getitem__(self, index):
224 return self._children[index]
225
226 def __setitem__(self, index, element):
227 if isinstance(index, slice):
228 for elt in element:
229 self._assert_is_element(elt)
230 else:
231 self._assert_is_element(element)
232 self._children[index] = element
233
234 def __delitem__(self, index):
235 del self._children[index]
236
237 def append(self, subelement):
238 """Add *subelement* to the end of this element.
239
240 The new element will appear in document order after the last existing
241 subelement (or directly after the text, if it's the first subelement),
242 but before the end tag for this element.
243
244 """
245 self._assert_is_element(subelement)
246 self._children.append(subelement)
247
248 def extend(self, elements):
249 """Append subelements from a sequence.
250
251 *elements* is a sequence with zero or more elements.
252
253 """
254 for element in elements:
255 self._assert_is_element(element)
256 self._children.append(element)
257
258 def insert(self, index, subelement):
259 """Insert *subelement* at position *index*."""
260 self._assert_is_element(subelement)
261 self._children.insert(index, subelement)
262
263 def _assert_is_element(self, e):
264 # Need to refer to the actual Python implementation, not the
265 # shadowing C implementation.
266 if not isinstance(e, _Element_Py):
267 raise TypeError('expected an Element, not %s' % type(e).__name__)
268
269 def remove(self, subelement):
270 """Remove matching subelement.
271
272 Unlike the find methods, this method compares elements based on
273 identity, NOT ON tag value or contents. To remove subelements by
274 other means, the easiest way is to use a list comprehension to
275 select what elements to keep, and then use slice assignment to update
276 the parent element.
277
278 ValueError is raised if a matching element could not be found.
279
280 """
281 # assert iselement(element)
282 self._children.remove(subelement)
283
284 def find(self, path, namespaces=None):
285 """Find first matching element by tag name or path.
286
287 *path* is a string having either an element tag or an XPath,
288 *namespaces* is an optional mapping from namespace prefix to full name.
289
290 Return the first matching element, or None if no element was found.
291
292 """
293 return ElementPath.find(self, path, namespaces)
294
295 def findtext(self, path, default=None, namespaces=None):
296 """Find text for first matching element by tag name or path.
297
298 *path* is a string having either an element tag or an XPath,
299 *default* is the value to return if the element was not found,
300 *namespaces* is an optional mapping from namespace prefix to full name.
301
302 Return text content of first matching element, or default value if
303 none was found. Note that if an element is found having no text
304 content, the empty string is returned.
305
306 """
307 return ElementPath.findtext(self, path, default, namespaces)
308
309 def findall(self, path, namespaces=None):
310 """Find all matching subelements by tag name or path.
311
312 *path* is a string having either an element tag or an XPath,
313 *namespaces* is an optional mapping from namespace prefix to full name.
314
315 Returns list containing all matching elements in document order.
316
317 """
318 return ElementPath.findall(self, path, namespaces)
319
320 def iterfind(self, path, namespaces=None):
321 """Find all matching subelements by tag name or path.
322
323 *path* is a string having either an element tag or an XPath,
324 *namespaces* is an optional mapping from namespace prefix to full name.
325
326 Return an iterable yielding all matching elements in document order.
327
328 """
329 return ElementPath.iterfind(self, path, namespaces)
330
331 def clear(self):
332 """Reset element.
333
334 This function removes all subelements, clears all attributes, and sets
335 the text and tail attributes to None.
336
337 """
338 self.attrib.clear()
339 self._children = []
340 self.text = self.tail = None
341
342 def get(self, key, default=None):
343 """Get element attribute.
344
345 Equivalent to attrib.get, but some implementations may handle this a
346 bit more efficiently. *key* is what attribute to look for, and
347 *default* is what to return if the attribute was not found.
348
349 Returns a string containing the attribute value, or the default if
350 attribute was not found.
351
352 """
353 return self.attrib.get(key, default)
354
355 def set(self, key, value):
356 """Set element attribute.
357
358 Equivalent to attrib[key] = value, but some implementations may handle
359 this a bit more efficiently. *key* is what attribute to set, and
360 *value* is the attribute value to set it to.
361
362 """
363 self.attrib[key] = value
364
365 def keys(self):
366 """Get list of attribute names.
367
368 Names are returned in an arbitrary order, just like an ordinary
369 Python dict. Equivalent to attrib.keys()
370
371 """
372 return self.attrib.keys()
373
374 def items(self):
375 """Get element attributes as a sequence.
376
377 The attributes are returned in arbitrary order. Equivalent to
378 attrib.items().
379
380 Return a list of (name, value) tuples.
381
382 """
383 return self.attrib.items()
384
385 def iter(self, tag=None):
386 """Create tree iterator.
387
388 The iterator loops over the element and all subelements in document
389 order, returning all elements with a matching tag.
390
391 If the tree structure is modified during iteration, new or removed
392 elements may or may not be included. To get a stable set, use the
393 list() function on the iterator, and loop over the resulting list.
394
395 *tag* is what tags to look for (default is to return all elements)
396
397 Return an iterator containing all the matching elements.
398
399 """
400 if tag == "*":
401 tag = None
402 if tag is None or self.tag == tag:
403 yield self
404 for e in self._children:
405 yield from e.iter(tag)
406
407 def itertext(self):
408 """Create text iterator.
409
410 The iterator loops over the element and all subelements in document
411 order, returning all inner text.
412
413 """
414 tag = self.tag
415 if not isinstance(tag, str) and tag is not None:
416 return
417 t = self.text
418 if t:
419 yield t
420 for e in self:
421 yield from e.itertext()
422 t = e.tail
423 if t:
424 yield t
425
426
427 def SubElement(parent, tag, attrib={}, **extra):
428 """Subelement factory which creates an element instance, and appends it
429 to an existing parent.
430
431 The element tag, attribute names, and attribute values can be either
432 bytes or Unicode strings.
433
434 *parent* is the parent element, *tag* is the subelements name, *attrib* is
435 an optional directory containing element attributes, *extra* are
436 additional attributes given as keyword arguments.
437
438 """
439 attrib = {**attrib, **extra}
440 element = parent.makeelement(tag, attrib)
441 parent.append(element)
442 return element
443
444
445 def Comment(text=None):
446 """Comment element factory.
447
448 This function creates a special element which the standard serializer
449 serializes as an XML comment.
450
451 *text* is a string containing the comment string.
452
453 """
454 element = Element(Comment)
455 element.text = text
456 return element
457
458
459 def ProcessingInstruction(target, text=None):
460 """Processing Instruction element factory.
461
462 This function creates a special element which the standard serializer
463 serializes as an XML comment.
464
465 *target* is a string containing the processing instruction, *text* is a
466 string containing the processing instruction contents, if any.
467
468 """
469 element = Element(ProcessingInstruction)
470 element.text = target
471 if text:
472 element.text = element.text + " " + text
473 return element
474
475 PI = ProcessingInstruction
476
477
478 class QName:
479 """Qualified name wrapper.
480
481 This class can be used to wrap a QName attribute value in order to get
482 proper namespace handing on output.
483
484 *text_or_uri* is a string containing the QName value either in the form
485 {uri}local, or if the tag argument is given, the URI part of a QName.
486
487 *tag* is an optional argument which if given, will make the first
488 argument (text_or_uri) be interpreted as a URI, and this argument (tag)
489 be interpreted as a local name.
490
491 """
492 def __init__(self, text_or_uri, tag=None):
493 if tag:
494 text_or_uri = "{%s}%s" % (text_or_uri, tag)
495 self.text = text_or_uri
496 def __str__(self):
497 return self.text
498 def __repr__(self):
499 return '<%s %r>' % (self.__class__.__name__, self.text)
500 def __hash__(self):
501 return hash(self.text)
502 def __le__(self, other):
503 if isinstance(other, QName):
504 return self.text <= other.text
505 return self.text <= other
506 def __lt__(self, other):
507 if isinstance(other, QName):
508 return self.text < other.text
509 return self.text < other
510 def __ge__(self, other):
511 if isinstance(other, QName):
512 return self.text >= other.text
513 return self.text >= other
514 def __gt__(self, other):
515 if isinstance(other, QName):
516 return self.text > other.text
517 return self.text > other
518 def __eq__(self, other):
519 if isinstance(other, QName):
520 return self.text == other.text
521 return self.text == other
522
523 # --------------------------------------------------------------------
524
525
526 class ElementTree:
527 """An XML element hierarchy.
528
529 This class also provides support for serialization to and from
530 standard XML.
531
532 *element* is an optional root element node,
533 *file* is an optional file handle or file name of an XML file whose
534 contents will be used to initialize the tree with.
535
536 """
537 def __init__(self, element=None, file=None):
538 # assert element is None or iselement(element)
539 self._root = element # first node
540 if file:
541 self.parse(file)
542
543 def getroot(self):
544 """Return root element of this tree."""
545 return self._root
546
547 def _setroot(self, element):
548 """Replace root element of this tree.
549
550 This will discard the current contents of the tree and replace it
551 with the given element. Use with care!
552
553 """
554 # assert iselement(element)
555 self._root = element
556
557 def parse(self, source, parser=None):
558 """Load external XML document into element tree.
559
560 *source* is a file name or file object, *parser* is an optional parser
561 instance that defaults to XMLParser.
562
563 ParseError is raised if the parser fails to parse the document.
564
565 Returns the root element of the given source document.
566
567 """
568 close_source = False
569 if not hasattr(source, "read"):
570 source = open(source, "rb")
571 close_source = True
572 try:
573 if parser is None:
574 # If no parser was specified, create a default XMLParser
575 parser = XMLParser()
576 if hasattr(parser, '_parse_whole'):
577 # The default XMLParser, when it comes from an accelerator,
578 # can define an internal _parse_whole API for efficiency.
579 # It can be used to parse the whole source without feeding
580 # it with chunks.
581 self._root = parser._parse_whole(source)
582 return self._root
583 while True:
584 data = source.read(65536)
585 if not data:
586 break
587 parser.feed(data)
588 self._root = parser.close()
589 return self._root
590 finally:
591 if close_source:
592 source.close()
593
594 def iter(self, tag=None):
595 """Create and return tree iterator for the root element.
596
597 The iterator loops over all elements in this tree, in document order.
598
599 *tag* is a string with the tag name to iterate over
600 (default is to return all elements).
601
602 """
603 # assert self._root is not None
604 return self._root.iter(tag)
605
606 def find(self, path, namespaces=None):
607 """Find first matching element by tag name or path.
608
609 Same as getroot().find(path), which is Element.find()
610
611 *path* is a string having either an element tag or an XPath,
612 *namespaces* is an optional mapping from namespace prefix to full name.
613
614 Return the first matching element, or None if no element was found.
615
616 """
617 # assert self._root is not None
618 if path[:1] == "/":
619 path = "." + path
620 warnings.warn(
621 "This search is broken in 1.3 and earlier, and will be "
622 "fixed in a future version. If you rely on the current "
623 "behaviour, change it to %r" % path,
624 FutureWarning, stacklevel=2
625 )
626 return self._root.find(path, namespaces)
627
628 def findtext(self, path, default=None, namespaces=None):
629 """Find first matching element by tag name or path.
630
631 Same as getroot().findtext(path), which is Element.findtext()
632
633 *path* is a string having either an element tag or an XPath,
634 *namespaces* is an optional mapping from namespace prefix to full name.
635
636 Return the first matching element, or None if no element was found.
637
638 """
639 # assert self._root is not None
640 if path[:1] == "/":
641 path = "." + path
642 warnings.warn(
643 "This search is broken in 1.3 and earlier, and will be "
644 "fixed in a future version. If you rely on the current "
645 "behaviour, change it to %r" % path,
646 FutureWarning, stacklevel=2
647 )
648 return self._root.findtext(path, default, namespaces)
649
650 def findall(self, path, namespaces=None):
651 """Find all matching subelements by tag name or path.
652
653 Same as getroot().findall(path), which is Element.findall().
654
655 *path* is a string having either an element tag or an XPath,
656 *namespaces* is an optional mapping from namespace prefix to full name.
657
658 Return list containing all matching elements in document order.
659
660 """
661 # assert self._root is not None
662 if path[:1] == "/":
663 path = "." + path
664 warnings.warn(
665 "This search is broken in 1.3 and earlier, and will be "
666 "fixed in a future version. If you rely on the current "
667 "behaviour, change it to %r" % path,
668 FutureWarning, stacklevel=2
669 )
670 return self._root.findall(path, namespaces)
671
672 def iterfind(self, path, namespaces=None):
673 """Find all matching subelements by tag name or path.
674
675 Same as getroot().iterfind(path), which is element.iterfind()
676
677 *path* is a string having either an element tag or an XPath,
678 *namespaces* is an optional mapping from namespace prefix to full name.
679
680 Return an iterable yielding all matching elements in document order.
681
682 """
683 # assert self._root is not None
684 if path[:1] == "/":
685 path = "." + path
686 warnings.warn(
687 "This search is broken in 1.3 and earlier, and will be "
688 "fixed in a future version. If you rely on the current "
689 "behaviour, change it to %r" % path,
690 FutureWarning, stacklevel=2
691 )
692 return self._root.iterfind(path, namespaces)
693
694 def write(self, file_or_filename,
695 encoding=None,
696 xml_declaration=None,
697 default_namespace=None,
698 method=None, *,
699 short_empty_elements=True):
700 """Write element tree to a file as XML.
701
702 Arguments:
703 *file_or_filename* -- file name or a file object opened for writing
704
705 *encoding* -- the output encoding (default: US-ASCII)
706
707 *xml_declaration* -- bool indicating if an XML declaration should be
708 added to the output. If None, an XML declaration
709 is added if encoding IS NOT either of:
710 US-ASCII, UTF-8, or Unicode
711
712 *default_namespace* -- sets the default XML namespace (for "xmlns")
713
714 *method* -- either "xml" (default), "html, "text", or "c14n"
715
716 *short_empty_elements* -- controls the formatting of elements
717 that contain no content. If True (default)
718 they are emitted as a single self-closed
719 tag, otherwise they are emitted as a pair
720 of start/end tags
721
722 """
723 if not method:
724 method = "xml"
725 elif method not in _serialize:
726 raise ValueError("unknown method %r" % method)
727 if not encoding:
728 if method == "c14n":
729 encoding = "utf-8"
730 else:
731 encoding = "us-ascii"
732 with _get_writer(file_or_filename, encoding) as (write, declared_encoding):
733 if method == "xml" and (xml_declaration or
734 (xml_declaration is None and
735 encoding.lower() != "unicode" and
736 declared_encoding.lower() not in ("utf-8", "us-ascii"))):
737 write("<?xml version='1.0' encoding='%s'?>\n" % (
738 declared_encoding,))
739 if method == "text":
740 _serialize_text(write, self._root)
741 else:
742 qnames, namespaces = _namespaces(self._root, default_namespace)
743 serialize = _serialize[method]
744 serialize(write, self._root, qnames, namespaces,
745 short_empty_elements=short_empty_elements)
746
747 def write_c14n(self, file):
748 # lxml.etree compatibility. use output method instead
749 return self.write(file, method="c14n")
750
751 # --------------------------------------------------------------------
752 # serialization support
753
754 @contextlib.contextmanager
755 def _get_writer(file_or_filename, encoding):
756 # returns text write method and release all resources after using
757 try:
758 write = file_or_filename.write
759 except AttributeError:
760 # file_or_filename is a file name
761 if encoding.lower() == "unicode":
762 encoding="utf-8"
763 with open(file_or_filename, "w", encoding=encoding,
764 errors="xmlcharrefreplace") as file:
765 yield file.write, encoding
766 else:
767 # file_or_filename is a file-like object
768 # encoding determines if it is a text or binary writer
769 if encoding.lower() == "unicode":
770 # use a text writer as is
771 yield write, getattr(file_or_filename, "encoding", None) or "utf-8"
772 else:
773 # wrap a binary writer with TextIOWrapper
774 with contextlib.ExitStack() as stack:
775 if isinstance(file_or_filename, io.BufferedIOBase):
776 file = file_or_filename
777 elif isinstance(file_or_filename, io.RawIOBase):
778 file = io.BufferedWriter(file_or_filename)
779 # Keep the original file open when the BufferedWriter is
780 # destroyed
781 stack.callback(file.detach)
782 else:
783 # This is to handle passed objects that aren't in the
784 # IOBase hierarchy, but just have a write method
785 file = io.BufferedIOBase()
786 file.writable = lambda: True
787 file.write = write
788 try:
789 # TextIOWrapper uses this methods to determine
790 # if BOM (for UTF-16, etc) should be added
791 file.seekable = file_or_filename.seekable
792 file.tell = file_or_filename.tell
793 except AttributeError:
794 pass
795 file = io.TextIOWrapper(file,
796 encoding=encoding,
797 errors="xmlcharrefreplace",
798 newline="\n")
799 # Keep the original file open when the TextIOWrapper is
800 # destroyed
801 stack.callback(file.detach)
802 yield file.write, encoding
803
804 def _namespaces(elem, default_namespace=None):
805 # identify namespaces used in this tree
806
807 # maps qnames to *encoded* prefix:local names
808 qnames = {None: None}
809
810 # maps uri:s to prefixes
811 namespaces = {}
812 if default_namespace:
813 namespaces[default_namespace] = ""
814
815 def add_qname(qname):
816 # calculate serialized qname representation
817 try:
818 if qname[:1] == "{":
819 uri, tag = qname[1:].rsplit("}", 1)
820 prefix = namespaces.get(uri)
821 if prefix is None:
822 prefix = _namespace_map.get(uri)
823 if prefix is None:
824 prefix = "ns%d" % len(namespaces)
825 if prefix != "xml":
826 namespaces[uri] = prefix
827 if prefix:
828 qnames[qname] = "%s:%s" % (prefix, tag)
829 else:
830 qnames[qname] = tag # default element
831 else:
832 if default_namespace:
833 # FIXME: can this be handled in XML 1.0?
834 raise ValueError(
835 "cannot use non-qualified names with "
836 "default_namespace option"
837 )
838 qnames[qname] = qname
839 except TypeError:
840 _raise_serialization_error(qname)
841
842 # populate qname and namespaces table
843 for elem in elem.iter():
844 tag = elem.tag
845 if isinstance(tag, QName):
846 if tag.text not in qnames:
847 add_qname(tag.text)
848 elif isinstance(tag, str):
849 if tag not in qnames:
850 add_qname(tag)
851 elif tag is not None and tag is not Comment and tag is not PI:
852 _raise_serialization_error(tag)
853 for key, value in elem.items():
854 if isinstance(key, QName):
855 key = key.text
856 if key not in qnames:
857 add_qname(key)
858 if isinstance(value, QName) and value.text not in qnames:
859 add_qname(value.text)
860 text = elem.text
861 if isinstance(text, QName) and text.text not in qnames:
862 add_qname(text.text)
863 return qnames, namespaces
864
865 def _serialize_xml(write, elem, qnames, namespaces,
866 short_empty_elements, **kwargs):
867 tag = elem.tag
868 text = elem.text
869 if tag is Comment:
870 write("<!--%s-->" % text)
871 elif tag is ProcessingInstruction:
872 write("<?%s?>" % text)
873 else:
874 tag = qnames[tag]
875 if tag is None:
876 if text:
877 write(_escape_cdata(text))
878 for e in elem:
879 _serialize_xml(write, e, qnames, None,
880 short_empty_elements=short_empty_elements)
881 else:
882 write("<" + tag)
883 items = list(elem.items())
884 if items or namespaces:
885 if namespaces:
886 for v, k in sorted(namespaces.items(),
887 key=lambda x: x[1]): # sort on prefix
888 if k:
889 k = ":" + k
890 write(" xmlns%s=\"%s\"" % (
891 k,
892 _escape_attrib(v)
893 ))
894 for k, v in items:
895 if isinstance(k, QName):
896 k = k.text
897 if isinstance(v, QName):
898 v = qnames[v.text]
899 else:
900 v = _escape_attrib(v)
901 write(" %s=\"%s\"" % (qnames[k], v))
902 if text or len(elem) or not short_empty_elements:
903 write(">")
904 if text:
905 write(_escape_cdata(text))
906 for e in elem:
907 _serialize_xml(write, e, qnames, None,
908 short_empty_elements=short_empty_elements)
909 write("</" + tag + ">")
910 else:
911 write(" />")
912 if elem.tail:
913 write(_escape_cdata(elem.tail))
914
915 HTML_EMPTY = {"area", "base", "basefont", "br", "col", "embed", "frame", "hr",
916 "img", "input", "isindex", "link", "meta", "param", "source",
917 "track", "wbr"}
918
919 def _serialize_html(write, elem, qnames, namespaces, **kwargs):
920 tag = elem.tag
921 text = elem.text
922 if tag is Comment:
923 write("<!--%s-->" % _escape_cdata(text))
924 elif tag is ProcessingInstruction:
925 write("<?%s?>" % _escape_cdata(text))
926 else:
927 tag = qnames[tag]
928 if tag is None:
929 if text:
930 write(_escape_cdata(text))
931 for e in elem:
932 _serialize_html(write, e, qnames, None)
933 else:
934 write("<" + tag)
935 items = list(elem.items())
936 if items or namespaces:
937 if namespaces:
938 for v, k in sorted(namespaces.items(),
939 key=lambda x: x[1]): # sort on prefix
940 if k:
941 k = ":" + k
942 write(" xmlns%s=\"%s\"" % (
943 k,
944 _escape_attrib(v)
945 ))
946 for k, v in items:
947 if isinstance(k, QName):
948 k = k.text
949 if isinstance(v, QName):
950 v = qnames[v.text]
951 else:
952 v = _escape_attrib_html(v)
953 # FIXME: handle boolean attributes
954 write(" %s=\"%s\"" % (qnames[k], v))
955 write(">")
956 ltag = tag.lower()
957 if text:
958 if ltag == "script" or ltag == "style":
959 write(text)
960 else:
961 write(_escape_cdata(text))
962 for e in elem:
963 _serialize_html(write, e, qnames, None)
964 if ltag not in HTML_EMPTY:
965 write("</" + tag + ">")
966 if elem.tail:
967 write(_escape_cdata(elem.tail))
968
969 def _serialize_text(write, elem):
970 for part in elem.itertext():
971 write(part)
972 if elem.tail:
973 write(elem.tail)
974
975 _serialize = {
976 "xml": _serialize_xml,
977 "html": _serialize_html,
978 "text": _serialize_text,
979 # this optional method is imported at the end of the module
980 # "c14n": _serialize_c14n,
981 }
982
983
984 def register_namespace(prefix, uri):
985 """Register a namespace prefix.
986
987 The registry is global, and any existing mapping for either the
988 given prefix or the namespace URI will be removed.
989
990 *prefix* is the namespace prefix, *uri* is a namespace uri. Tags and
991 attributes in this namespace will be serialized with prefix if possible.
992
993 ValueError is raised if prefix is reserved or is invalid.
994
995 """
996 if re.match(r"ns\d+$", prefix):
997 raise ValueError("Prefix format reserved for internal use")
998 for k, v in list(_namespace_map.items()):
999 if k == uri or v == prefix:
1000 del _namespace_map[k]
1001 _namespace_map[uri] = prefix
1002
1003 _namespace_map = {
1004 # "well-known" namespace prefixes
1005 "http://www.w3.org/XML/1998/namespace": "xml",
1006 "http://www.w3.org/1999/xhtml": "html",
1007 "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf",
1008 "http://schemas.xmlsoap.org/wsdl/": "wsdl",
1009 # xml schema
1010 "http://www.w3.org/2001/XMLSchema": "xs",
1011 "http://www.w3.org/2001/XMLSchema-instance": "xsi",
1012 # dublin core
1013 "http://purl.org/dc/elements/1.1/": "dc",
1014 }
1015 # For tests and troubleshooting
1016 register_namespace._namespace_map = _namespace_map
1017
1018 def _raise_serialization_error(text):
1019 raise TypeError(
1020 "cannot serialize %r (type %s)" % (text, type(text).__name__)
1021 )
1022
1023 def _escape_cdata(text):
1024 # escape character data
1025 try:
1026 # it's worth avoiding do-nothing calls for strings that are
1027 # shorter than 500 characters, or so. assume that's, by far,
1028 # the most common case in most applications.
1029 if "&" in text:
1030 text = text.replace("&", "&amp;")
1031 if "<" in text:
1032 text = text.replace("<", "&lt;")
1033 if ">" in text:
1034 text = text.replace(">", "&gt;")
1035 return text
1036 except (TypeError, AttributeError):
1037 _raise_serialization_error(text)
1038
1039 def _escape_attrib(text):
1040 # escape attribute value
1041 try:
1042 if "&" in text:
1043 text = text.replace("&", "&amp;")
1044 if "<" in text:
1045 text = text.replace("<", "&lt;")
1046 if ">" in text:
1047 text = text.replace(">", "&gt;")
1048 if "\"" in text:
1049 text = text.replace("\"", "&quot;")
1050 # Although section 2.11 of the XML specification states that CR or
1051 # CR LN should be replaced with just LN, it applies only to EOLNs
1052 # which take part of organizing file into lines. Within attributes,
1053 # we are replacing these with entity numbers, so they do not count.
1054 # http://www.w3.org/TR/REC-xml/#sec-line-ends
1055 # The current solution, contained in following six lines, was
1056 # discussed in issue 17582 and 39011.
1057 if "\r" in text:
1058 text = text.replace("\r", "&#13;")
1059 if "\n" in text:
1060 text = text.replace("\n", "&#10;")
1061 if "\t" in text:
1062 text = text.replace("\t", "&#09;")
1063 return text
1064 except (TypeError, AttributeError):
1065 _raise_serialization_error(text)
1066
1067 def _escape_attrib_html(text):
1068 # escape attribute value
1069 try:
1070 if "&" in text:
1071 text = text.replace("&", "&amp;")
1072 if ">" in text:
1073 text = text.replace(">", "&gt;")
1074 if "\"" in text:
1075 text = text.replace("\"", "&quot;")
1076 return text
1077 except (TypeError, AttributeError):
1078 _raise_serialization_error(text)
1079
1080 # --------------------------------------------------------------------
1081
1082 def tostring(element, encoding=None, method=None, *,
1083 xml_declaration=None, default_namespace=None,
1084 short_empty_elements=True):
1085 """Generate string representation of XML element.
1086
1087 All subelements are included. If encoding is "unicode", a string
1088 is returned. Otherwise a bytestring is returned.
1089
1090 *element* is an Element instance, *encoding* is an optional output
1091 encoding defaulting to US-ASCII, *method* is an optional output which can
1092 be one of "xml" (default), "html", "text" or "c14n", *default_namespace*
1093 sets the default XML namespace (for "xmlns").
1094
1095 Returns an (optionally) encoded string containing the XML data.
1096
1097 """
1098 stream = io.StringIO() if encoding == 'unicode' else io.BytesIO()
1099 ElementTree(element).write(stream, encoding,
1100 xml_declaration=xml_declaration,
1101 default_namespace=default_namespace,
1102 method=method,
1103 short_empty_elements=short_empty_elements)
1104 return stream.getvalue()
1105
1106 class _ListDataStream(io.BufferedIOBase):
1107 """An auxiliary stream accumulating into a list reference."""
1108 def __init__(self, lst):
1109 self.lst = lst
1110
1111 def writable(self):
1112 return True
1113
1114 def seekable(self):
1115 return True
1116
1117 def write(self, b):
1118 self.lst.append(b)
1119
1120 def tell(self):
1121 return len(self.lst)
1122
1123 def tostringlist(element, encoding=None, method=None, *,
1124 xml_declaration=None, default_namespace=None,
1125 short_empty_elements=True):
1126 lst = []
1127 stream = _ListDataStream(lst)
1128 ElementTree(element).write(stream, encoding,
1129 xml_declaration=xml_declaration,
1130 default_namespace=default_namespace,
1131 method=method,
1132 short_empty_elements=short_empty_elements)
1133 return lst
1134
1135
1136 def dump(elem):
1137 """Write element tree or element structure to sys.stdout.
1138
1139 This function should be used for debugging only.
1140
1141 *elem* is either an ElementTree, or a single Element. The exact output
1142 format is implementation dependent. In this version, it's written as an
1143 ordinary XML file.
1144
1145 """
1146 # debugging
1147 if not isinstance(elem, ElementTree):
1148 elem = ElementTree(elem)
1149 elem.write(sys.stdout, encoding="unicode")
1150 tail = elem.getroot().tail
1151 if not tail or tail[-1] != "\n":
1152 sys.stdout.write("\n")
1153
1154
1155 def indent(tree, space=" ", level=0):
1156 """Indent an XML document by inserting newlines and indentation space
1157 after elements.
1158
1159 *tree* is the ElementTree or Element to modify. The (root) element
1160 itself will not be changed, but the tail text of all elements in its
1161 subtree will be adapted.
1162
1163 *space* is the whitespace to insert for each indentation level, two
1164 space characters by default.
1165
1166 *level* is the initial indentation level. Setting this to a higher
1167 value than 0 can be used for indenting subtrees that are more deeply
1168 nested inside of a document.
1169 """
1170 if isinstance(tree, ElementTree):
1171 tree = tree.getroot()
1172 if level < 0:
1173 raise ValueError(f"Initial indentation level must be >= 0, got {level}")
1174 if not len(tree):
1175 return
1176
1177 # Reduce the memory consumption by reusing indentation strings.
1178 indentations = ["\n" + level * space]
1179
1180 def _indent_children(elem, level):
1181 # Start a new indentation level for the first child.
1182 child_level = level + 1
1183 try:
1184 child_indentation = indentations[child_level]
1185 except IndexError:
1186 child_indentation = indentations[level] + space
1187 indentations.append(child_indentation)
1188
1189 if not elem.text or not elem.text.strip():
1190 elem.text = child_indentation
1191
1192 for child in elem:
1193 if len(child):
1194 _indent_children(child, child_level)
1195 if not child.tail or not child.tail.strip():
1196 child.tail = child_indentation
1197
1198 # Dedent after the last child by overwriting the previous indentation.
1199 if not child.tail.strip():
1200 child.tail = indentations[level]
1201
1202 _indent_children(tree, 0)
1203
1204
1205 # --------------------------------------------------------------------
1206 # parsing
1207
1208
1209 def parse(source, parser=None):
1210 """Parse XML document into element tree.
1211
1212 *source* is a filename or file object containing XML data,
1213 *parser* is an optional parser instance defaulting to XMLParser.
1214
1215 Return an ElementTree instance.
1216
1217 """
1218 tree = ElementTree()
1219 tree.parse(source, parser)
1220 return tree
1221
1222
1223 def iterparse(source, events=None, parser=None):
1224 """Incrementally parse XML document into ElementTree.
1225
1226 This class also reports what's going on to the user based on the
1227 *events* it is initialized with. The supported events are the strings
1228 "start", "end", "start-ns" and "end-ns" (the "ns" events are used to get
1229 detailed namespace information). If *events* is omitted, only
1230 "end" events are reported.
1231
1232 *source* is a filename or file object containing XML data, *events* is
1233 a list of events to report back, *parser* is an optional parser instance.
1234
1235 Returns an iterator providing (event, elem) pairs.
1236
1237 """
1238 # Use the internal, undocumented _parser argument for now; When the
1239 # parser argument of iterparse is removed, this can be killed.
1240 pullparser = XMLPullParser(events=events, _parser=parser)
1241
1242 if not hasattr(source, "read"):
1243 source = open(source, "rb")
1244 close_source = True
1245 else:
1246 close_source = False
1247
1248 def iterator(source):
1249 try:
1250 while True:
1251 yield from pullparser.read_events()
1252 # load event buffer
1253 data = source.read(16 * 1024)
1254 if not data:
1255 break
1256 pullparser.feed(data)
1257 root = pullparser._close_and_return_root()
1258 yield from pullparser.read_events()
1259 it = wr()
1260 if it is not None:
1261 it.root = root
1262 finally:
1263 if close_source:
1264 source.close()
1265
1266 class IterParseIterator(collections.abc.Iterator):
1267 __next__ = iterator(source).__next__
1268
1269 def __del__(self):
1270 if close_source:
1271 source.close()
1272
1273 it = IterParseIterator()
1274 it.root = None
1275 wr = weakref.ref(it)
1276 return it
1277
1278
1279 class XMLPullParser:
1280
1281 def __init__(self, events=None, *, _parser=None):
1282 # The _parser argument is for internal use only and must not be relied
1283 # upon in user code. It will be removed in a future release.
1284 # See https://bugs.python.org/issue17741 for more details.
1285
1286 self._events_queue = collections.deque()
1287 self._parser = _parser or XMLParser(target=TreeBuilder())
1288 # wire up the parser for event reporting
1289 if events is None:
1290 events = ("end",)
1291 self._parser._setevents(self._events_queue, events)
1292
1293 def feed(self, data):
1294 """Feed encoded data to parser."""
1295 if self._parser is None:
1296 raise ValueError("feed() called after end of stream")
1297 if data:
1298 try:
1299 self._parser.feed(data)
1300 except SyntaxError as exc:
1301 self._events_queue.append(exc)
1302
1303 def _close_and_return_root(self):
1304 # iterparse needs this to set its root attribute properly :(
1305 root = self._parser.close()
1306 self._parser = None
1307 return root
1308
1309 def close(self):
1310 """Finish feeding data to parser.
1311
1312 Unlike XMLParser, does not return the root element. Use
1313 read_events() to consume elements from XMLPullParser.
1314 """
1315 self._close_and_return_root()
1316
1317 def read_events(self):
1318 """Return an iterator over currently available (event, elem) pairs.
1319
1320 Events are consumed from the internal event queue as they are
1321 retrieved from the iterator.
1322 """
1323 events = self._events_queue
1324 while events:
1325 event = events.popleft()
1326 if isinstance(event, Exception):
1327 raise event
1328 else:
1329 yield event
1330
1331 def flush(self):
1332 if self._parser is None:
1333 raise ValueError("flush() called after end of stream")
1334 self._parser.flush()
1335
1336
1337 def XML(text, parser=None):
1338 """Parse XML document from string constant.
1339
1340 This function can be used to embed "XML Literals" in Python code.
1341
1342 *text* is a string containing XML data, *parser* is an
1343 optional parser instance, defaulting to the standard XMLParser.
1344
1345 Returns an Element instance.
1346
1347 """
1348 if not parser:
1349 parser = XMLParser(target=TreeBuilder())
1350 parser.feed(text)
1351 return parser.close()
1352
1353
1354 def XMLID(text, parser=None):
1355 """Parse XML document from string constant for its IDs.
1356
1357 *text* is a string containing XML data, *parser* is an
1358 optional parser instance, defaulting to the standard XMLParser.
1359
1360 Returns an (Element, dict) tuple, in which the
1361 dict maps element id:s to elements.
1362
1363 """
1364 if not parser:
1365 parser = XMLParser(target=TreeBuilder())
1366 parser.feed(text)
1367 tree = parser.close()
1368 ids = {}
1369 for elem in tree.iter():
1370 id = elem.get("id")
1371 if id:
1372 ids[id] = elem
1373 return tree, ids
1374
1375 # Parse XML document from string constant. Alias for XML().
1376 fromstring = XML
1377
1378 def fromstringlist(sequence, parser=None):
1379 """Parse XML document from sequence of string fragments.
1380
1381 *sequence* is a list of other sequence, *parser* is an optional parser
1382 instance, defaulting to the standard XMLParser.
1383
1384 Returns an Element instance.
1385
1386 """
1387 if not parser:
1388 parser = XMLParser(target=TreeBuilder())
1389 for text in sequence:
1390 parser.feed(text)
1391 return parser.close()
1392
1393 # --------------------------------------------------------------------
1394
1395
1396 class TreeBuilder:
1397 """Generic element structure builder.
1398
1399 This builder converts a sequence of start, data, and end method
1400 calls to a well-formed element structure.
1401
1402 You can use this class to build an element structure using a custom XML
1403 parser, or a parser for some other XML-like format.
1404
1405 *element_factory* is an optional element factory which is called
1406 to create new Element instances, as necessary.
1407
1408 *comment_factory* is a factory to create comments to be used instead of
1409 the standard factory. If *insert_comments* is false (the default),
1410 comments will not be inserted into the tree.
1411
1412 *pi_factory* is a factory to create processing instructions to be used
1413 instead of the standard factory. If *insert_pis* is false (the default),
1414 processing instructions will not be inserted into the tree.
1415 """
1416 def __init__(self, element_factory=None, *,
1417 comment_factory=None, pi_factory=None,
1418 insert_comments=False, insert_pis=False):
1419 self._data = [] # data collector
1420 self._elem = [] # element stack
1421 self._last = None # last element
1422 self._root = None # root element
1423 self._tail = None # true if we're after an end tag
1424 if comment_factory is None:
1425 comment_factory = Comment
1426 self._comment_factory = comment_factory
1427 self.insert_comments = insert_comments
1428 if pi_factory is None:
1429 pi_factory = ProcessingInstruction
1430 self._pi_factory = pi_factory
1431 self.insert_pis = insert_pis
1432 if element_factory is None:
1433 element_factory = Element
1434 self._factory = element_factory
1435
1436 def close(self):
1437 """Flush builder buffers and return toplevel document Element."""
1438 assert len(self._elem) == 0, "missing end tags"
1439 assert self._root is not None, "missing toplevel element"
1440 return self._root
1441
1442 def _flush(self):
1443 if self._data:
1444 if self._last is not None:
1445 text = "".join(self._data)
1446 if self._tail:
1447 assert self._last.tail is None, "internal error (tail)"
1448 self._last.tail = text
1449 else:
1450 assert self._last.text is None, "internal error (text)"
1451 self._last.text = text
1452 self._data = []
1453
1454 def data(self, data):
1455 """Add text to current element."""
1456 self._data.append(data)
1457
1458 def start(self, tag, attrs):
1459 """Open new element and return it.
1460
1461 *tag* is the element name, *attrs* is a dict containing element
1462 attributes.
1463
1464 """
1465 self._flush()
1466 self._last = elem = self._factory(tag, attrs)
1467 if self._elem:
1468 self._elem[-1].append(elem)
1469 elif self._root is None:
1470 self._root = elem
1471 self._elem.append(elem)
1472 self._tail = 0
1473 return elem
1474
1475 def end(self, tag):
1476 """Close and return current Element.
1477
1478 *tag* is the element name.
1479
1480 """
1481 self._flush()
1482 self._last = self._elem.pop()
1483 assert self._last.tag == tag,\
1484 "end tag mismatch (expected %s, got %s)" % (
1485 self._last.tag, tag)
1486 self._tail = 1
1487 return self._last
1488
1489 def comment(self, text):
1490 """Create a comment using the comment_factory.
1491
1492 *text* is the text of the comment.
1493 """
1494 return self._handle_single(
1495 self._comment_factory, self.insert_comments, text)
1496
1497 def pi(self, target, text=None):
1498 """Create a processing instruction using the pi_factory.
1499
1500 *target* is the target name of the processing instruction.
1501 *text* is the data of the processing instruction, or ''.
1502 """
1503 return self._handle_single(
1504 self._pi_factory, self.insert_pis, target, text)
1505
1506 def _handle_single(self, factory, insert, *args):
1507 elem = factory(*args)
1508 if insert:
1509 self._flush()
1510 self._last = elem
1511 if self._elem:
1512 self._elem[-1].append(elem)
1513 self._tail = 1
1514 return elem
1515
1516
1517 # also see ElementTree and TreeBuilder
1518 class XMLParser:
1519 """Element structure builder for XML source data based on the expat parser.
1520
1521 *target* is an optional target object which defaults to an instance of the
1522 standard TreeBuilder class, *encoding* is an optional encoding string
1523 which if given, overrides the encoding specified in the XML file:
1524 http://www.iana.org/assignments/character-sets
1525
1526 """
1527
1528 def __init__(self, *, target=None, encoding=None):
1529 try:
1530 from xml.parsers import expat
1531 except ImportError:
1532 try:
1533 import pyexpat as expat
1534 except ImportError:
1535 raise ImportError(
1536 "No module named expat; use SimpleXMLTreeBuilder instead"
1537 )
1538 parser = expat.ParserCreate(encoding, "}")
1539 if target is None:
1540 target = TreeBuilder()
1541 # underscored names are provided for compatibility only
1542 self.parser = self._parser = parser
1543 self.target = self._target = target
1544 self._error = expat.error
1545 self._names = {} # name memo cache
1546 # main callbacks
1547 parser.DefaultHandlerExpand = self._default
1548 if hasattr(target, 'start'):
1549 parser.StartElementHandler = self._start
1550 if hasattr(target, 'end'):
1551 parser.EndElementHandler = self._end
1552 if hasattr(target, 'start_ns'):
1553 parser.StartNamespaceDeclHandler = self._start_ns
1554 if hasattr(target, 'end_ns'):
1555 parser.EndNamespaceDeclHandler = self._end_ns
1556 if hasattr(target, 'data'):
1557 parser.CharacterDataHandler = target.data
1558 # miscellaneous callbacks
1559 if hasattr(target, 'comment'):
1560 parser.CommentHandler = target.comment
1561 if hasattr(target, 'pi'):
1562 parser.ProcessingInstructionHandler = target.pi
1563 # Configure pyexpat: buffering, new-style attribute handling.
1564 parser.buffer_text = 1
1565 parser.ordered_attributes = 1
1566 self._doctype = None
1567 self.entity = {}
1568 try:
1569 self.version = "Expat %d.%d.%d" % expat.version_info
1570 except AttributeError:
1571 pass # unknown
1572
1573 def _setevents(self, events_queue, events_to_report):
1574 # Internal API for XMLPullParser
1575 # events_to_report: a list of events to report during parsing (same as
1576 # the *events* of XMLPullParser's constructor.
1577 # events_queue: a list of actual parsing events that will be populated
1578 # by the underlying parser.
1579 #
1580 parser = self._parser
1581 append = events_queue.append
1582 for event_name in events_to_report:
1583 if event_name == "start":
1584 parser.ordered_attributes = 1
1585 def handler(tag, attrib_in, event=event_name, append=append,
1586 start=self._start):
1587 append((event, start(tag, attrib_in)))
1588 parser.StartElementHandler = handler
1589 elif event_name == "end":
1590 def handler(tag, event=event_name, append=append,
1591 end=self._end):
1592 append((event, end(tag)))
1593 parser.EndElementHandler = handler
1594 elif event_name == "start-ns":
1595 # TreeBuilder does not implement .start_ns()
1596 if hasattr(self.target, "start_ns"):
1597 def handler(prefix, uri, event=event_name, append=append,
1598 start_ns=self._start_ns):
1599 append((event, start_ns(prefix, uri)))
1600 else:
1601 def handler(prefix, uri, event=event_name, append=append):
1602 append((event, (prefix or '', uri or '')))
1603 parser.StartNamespaceDeclHandler = handler
1604 elif event_name == "end-ns":
1605 # TreeBuilder does not implement .end_ns()
1606 if hasattr(self.target, "end_ns"):
1607 def handler(prefix, event=event_name, append=append,
1608 end_ns=self._end_ns):
1609 append((event, end_ns(prefix)))
1610 else:
1611 def handler(prefix, event=event_name, append=append):
1612 append((event, None))
1613 parser.EndNamespaceDeclHandler = handler
1614 elif event_name == 'comment':
1615 def handler(text, event=event_name, append=append, self=self):
1616 append((event, self.target.comment(text)))
1617 parser.CommentHandler = handler
1618 elif event_name == 'pi':
1619 def handler(pi_target, data, event=event_name, append=append,
1620 self=self):
1621 append((event, self.target.pi(pi_target, data)))
1622 parser.ProcessingInstructionHandler = handler
1623 else:
1624 raise ValueError("unknown event %r" % event_name)
1625
1626 def _raiseerror(self, value):
1627 err = ParseError(value)
1628 err.code = value.code
1629 err.position = value.lineno, value.offset
1630 raise err
1631
1632 def _fixname(self, key):
1633 # expand qname, and convert name string to ascii, if possible
1634 try:
1635 name = self._names[key]
1636 except KeyError:
1637 name = key
1638 if "}" in name:
1639 name = "{" + name
1640 self._names[key] = name
1641 return name
1642
1643 def _start_ns(self, prefix, uri):
1644 return self.target.start_ns(prefix or '', uri or '')
1645
1646 def _end_ns(self, prefix):
1647 return self.target.end_ns(prefix or '')
1648
1649 def _start(self, tag, attr_list):
1650 # Handler for expat's StartElementHandler. Since ordered_attributes
1651 # is set, the attributes are reported as a list of alternating
1652 # attribute name,value.
1653 fixname = self._fixname
1654 tag = fixname(tag)
1655 attrib = {}
1656 if attr_list:
1657 for i in range(0, len(attr_list), 2):
1658 attrib[fixname(attr_list[i])] = attr_list[i+1]
1659 return self.target.start(tag, attrib)
1660
1661 def _end(self, tag):
1662 return self.target.end(self._fixname(tag))
1663
1664 def _default(self, text):
1665 prefix = text[:1]
1666 if prefix == "&":
1667 # deal with undefined entities
1668 try:
1669 data_handler = self.target.data
1670 except AttributeError:
1671 return
1672 try:
1673 data_handler(self.entity[text[1:-1]])
1674 except KeyError:
1675 from xml.parsers import expat
1676 err = expat.error(
1677 "undefined entity %s: line %d, column %d" %
1678 (text, self.parser.ErrorLineNumber,
1679 self.parser.ErrorColumnNumber)
1680 )
1681 err.code = 11 # XML_ERROR_UNDEFINED_ENTITY
1682 err.lineno = self.parser.ErrorLineNumber
1683 err.offset = self.parser.ErrorColumnNumber
1684 raise err
1685 elif prefix == "<" and text[:9] == "<!DOCTYPE":
1686 self._doctype = [] # inside a doctype declaration
1687 elif self._doctype is not None:
1688 # parse doctype contents
1689 if prefix == ">":
1690 self._doctype = None
1691 return
1692 text = text.strip()
1693 if not text:
1694 return
1695 self._doctype.append(text)
1696 n = len(self._doctype)
1697 if n > 2:
1698 type = self._doctype[1]
1699 if type == "PUBLIC" and n == 4:
1700 name, type, pubid, system = self._doctype
1701 if pubid:
1702 pubid = pubid[1:-1]
1703 elif type == "SYSTEM" and n == 3:
1704 name, type, system = self._doctype
1705 pubid = None
1706 else:
1707 return
1708 if hasattr(self.target, "doctype"):
1709 self.target.doctype(name, pubid, system[1:-1])
1710 elif hasattr(self, "doctype"):
1711 warnings.warn(
1712 "The doctype() method of XMLParser is ignored. "
1713 "Define doctype() method on the TreeBuilder target.",
1714 RuntimeWarning)
1715
1716 self._doctype = None
1717
1718 def feed(self, data):
1719 """Feed encoded data to parser."""
1720 try:
1721 self.parser.Parse(data, False)
1722 except self._error as v:
1723 self._raiseerror(v)
1724
1725 def close(self):
1726 """Finish feeding data to parser and return element structure."""
1727 try:
1728 self.parser.Parse(b"", True) # end of data
1729 except self._error as v:
1730 self._raiseerror(v)
1731 try:
1732 close_handler = self.target.close
1733 except AttributeError:
1734 pass
1735 else:
1736 return close_handler()
1737 finally:
1738 # get rid of circular references
1739 del self.parser, self._parser
1740 del self.target, self._target
1741
1742 def flush(self):
1743 was_enabled = self.parser.GetReparseDeferralEnabled()
1744 try:
1745 self.parser.SetReparseDeferralEnabled(False)
1746 self.parser.Parse(b"", False)
1747 except self._error as v:
1748 self._raiseerror(v)
1749 finally:
1750 self.parser.SetReparseDeferralEnabled(was_enabled)
1751
1752 # --------------------------------------------------------------------
1753 # C14N 2.0
1754
1755 def canonicalize(xml_data=None, *, out=None, from_file=None, **options):
1756 """Convert XML to its C14N 2.0 serialised form.
1757
1758 If *out* is provided, it must be a file or file-like object that receives
1759 the serialised canonical XML output (text, not bytes) through its ``.write()``
1760 method. To write to a file, open it in text mode with encoding "utf-8".
1761 If *out* is not provided, this function returns the output as text string.
1762
1763 Either *xml_data* (an XML string) or *from_file* (a file path or
1764 file-like object) must be provided as input.
1765
1766 The configuration options are the same as for the ``C14NWriterTarget``.
1767 """
1768 if xml_data is None and from_file is None:
1769 raise ValueError("Either 'xml_data' or 'from_file' must be provided as input")
1770 sio = None
1771 if out is None:
1772 sio = out = io.StringIO()
1773
1774 parser = XMLParser(target=C14NWriterTarget(out.write, **options))
1775
1776 if xml_data is not None:
1777 parser.feed(xml_data)
1778 parser.close()
1779 elif from_file is not None:
1780 parse(from_file, parser=parser)
1781
1782 return sio.getvalue() if sio is not None else None
1783
1784
1785 _looks_like_prefix_name = re.compile(r'^\w+:\w+$', re.UNICODE).match
1786
1787
1788 class C14NWriterTarget:
1789 """
1790 Canonicalization writer target for the XMLParser.
1791
1792 Serialises parse events to XML C14N 2.0.
1793
1794 The *write* function is used for writing out the resulting data stream
1795 as text (not bytes). To write to a file, open it in text mode with encoding
1796 "utf-8" and pass its ``.write`` method.
1797
1798 Configuration options:
1799
1800 - *with_comments*: set to true to include comments
1801 - *strip_text*: set to true to strip whitespace before and after text content
1802 - *rewrite_prefixes*: set to true to replace namespace prefixes by "n{number}"
1803 - *qname_aware_tags*: a set of qname aware tag names in which prefixes
1804 should be replaced in text content
1805 - *qname_aware_attrs*: a set of qname aware attribute names in which prefixes
1806 should be replaced in text content
1807 - *exclude_attrs*: a set of attribute names that should not be serialised
1808 - *exclude_tags*: a set of tag names that should not be serialised
1809 """
1810 def __init__(self, write, *,
1811 with_comments=False, strip_text=False, rewrite_prefixes=False,
1812 qname_aware_tags=None, qname_aware_attrs=None,
1813 exclude_attrs=None, exclude_tags=None):
1814 self._write = write
1815 self._data = []
1816 self._with_comments = with_comments
1817 self._strip_text = strip_text
1818 self._exclude_attrs = set(exclude_attrs) if exclude_attrs else None
1819 self._exclude_tags = set(exclude_tags) if exclude_tags else None
1820
1821 self._rewrite_prefixes = rewrite_prefixes
1822 if qname_aware_tags:
1823 self._qname_aware_tags = set(qname_aware_tags)
1824 else:
1825 self._qname_aware_tags = None
1826 if qname_aware_attrs:
1827 self._find_qname_aware_attrs = set(qname_aware_attrs).intersection
1828 else:
1829 self._find_qname_aware_attrs = None
1830
1831 # Stack with globally and newly declared namespaces as (uri, prefix) pairs.
1832 self._declared_ns_stack = [[
1833 ("http://www.w3.org/XML/1998/namespace", "xml"),
1834 ]]
1835 # Stack with user declared namespace prefixes as (uri, prefix) pairs.
1836 self._ns_stack = []
1837 if not rewrite_prefixes:
1838 self._ns_stack.append(list(_namespace_map.items()))
1839 self._ns_stack.append([])
1840 self._prefix_map = {}
1841 self._preserve_space = [False]
1842 self._pending_start = None
1843 self._root_seen = False
1844 self._root_done = False
1845 self._ignored_depth = 0
1846
1847 def _iter_namespaces(self, ns_stack, _reversed=reversed):
1848 for namespaces in _reversed(ns_stack):
1849 if namespaces: # almost no element declares new namespaces
1850 yield from namespaces
1851
1852 def _resolve_prefix_name(self, prefixed_name):
1853 prefix, name = prefixed_name.split(':', 1)
1854 for uri, p in self._iter_namespaces(self._ns_stack):
1855 if p == prefix:
1856 return f'{{{uri}}}{name}'
1857 raise ValueError(f'Prefix {prefix} of QName "{prefixed_name}" is not declared in scope')
1858
1859 def _qname(self, qname, uri=None):
1860 if uri is None:
1861 uri, tag = qname[1:].rsplit('}', 1) if qname[:1] == '{' else ('', qname)
1862 else:
1863 tag = qname
1864
1865 prefixes_seen = set()
1866 for u, prefix in self._iter_namespaces(self._declared_ns_stack):
1867 if u == uri and prefix not in prefixes_seen:
1868 return f'{prefix}:{tag}' if prefix else tag, tag, uri
1869 prefixes_seen.add(prefix)
1870
1871 # Not declared yet => add new declaration.
1872 if self._rewrite_prefixes:
1873 if uri in self._prefix_map:
1874 prefix = self._prefix_map[uri]
1875 else:
1876 prefix = self._prefix_map[uri] = f'n{len(self._prefix_map)}'
1877 self._declared_ns_stack[-1].append((uri, prefix))
1878 return f'{prefix}:{tag}', tag, uri
1879
1880 if not uri and '' not in prefixes_seen:
1881 # No default namespace declared => no prefix needed.
1882 return tag, tag, uri
1883
1884 for u, prefix in self._iter_namespaces(self._ns_stack):
1885 if u == uri:
1886 self._declared_ns_stack[-1].append((uri, prefix))
1887 return f'{prefix}:{tag}' if prefix else tag, tag, uri
1888
1889 if not uri:
1890 # As soon as a default namespace is defined,
1891 # anything that has no namespace (and thus, no prefix) goes there.
1892 return tag, tag, uri
1893
1894 raise ValueError(f'Namespace "{uri}" is not declared in scope')
1895
1896 def data(self, data):
1897 if not self._ignored_depth:
1898 self._data.append(data)
1899
1900 def _flush(self, _join_text=''.join):
1901 data = _join_text(self._data)
1902 del self._data[:]
1903 if self._strip_text and not self._preserve_space[-1]:
1904 data = data.strip()
1905 if self._pending_start is not None:
1906 args, self._pending_start = self._pending_start, None
1907 qname_text = data if data and _looks_like_prefix_name(data) else None
1908 self._start(*args, qname_text)
1909 if qname_text is not None:
1910 return
1911 if data and self._root_seen:
1912 self._write(_escape_cdata_c14n(data))
1913
1914 def start_ns(self, prefix, uri):
1915 if self._ignored_depth:
1916 return
1917 # we may have to resolve qnames in text content
1918 if self._data:
1919 self._flush()
1920 self._ns_stack[-1].append((uri, prefix))
1921
1922 def start(self, tag, attrs):
1923 if self._exclude_tags is not None and (
1924 self._ignored_depth or tag in self._exclude_tags):
1925 self._ignored_depth += 1
1926 return
1927 if self._data:
1928 self._flush()
1929
1930 new_namespaces = []
1931 self._declared_ns_stack.append(new_namespaces)
1932
1933 if self._qname_aware_tags is not None and tag in self._qname_aware_tags:
1934 # Need to parse text first to see if it requires a prefix declaration.
1935 self._pending_start = (tag, attrs, new_namespaces)
1936 return
1937 self._start(tag, attrs, new_namespaces)
1938
1939 def _start(self, tag, attrs, new_namespaces, qname_text=None):
1940 if self._exclude_attrs is not None and attrs:
1941 attrs = {k: v for k, v in attrs.items() if k not in self._exclude_attrs}
1942
1943 qnames = {tag, *attrs}
1944 resolved_names = {}
1945
1946 # Resolve prefixes in attribute and tag text.
1947 if qname_text is not None:
1948 qname = resolved_names[qname_text] = self._resolve_prefix_name(qname_text)
1949 qnames.add(qname)
1950 if self._find_qname_aware_attrs is not None and attrs:
1951 qattrs = self._find_qname_aware_attrs(attrs)
1952 if qattrs:
1953 for attr_name in qattrs:
1954 value = attrs[attr_name]
1955 if _looks_like_prefix_name(value):
1956 qname = resolved_names[value] = self._resolve_prefix_name(value)
1957 qnames.add(qname)
1958 else:
1959 qattrs = None
1960 else:
1961 qattrs = None
1962
1963 # Assign prefixes in lexicographical order of used URIs.
1964 parse_qname = self._qname
1965 parsed_qnames = {n: parse_qname(n) for n in sorted(
1966 qnames, key=lambda n: n.split('}', 1))}
1967
1968 # Write namespace declarations in prefix order ...
1969 if new_namespaces:
1970 attr_list = [
1971 ('xmlns:' + prefix if prefix else 'xmlns', uri)
1972 for uri, prefix in new_namespaces
1973 ]
1974 attr_list.sort()
1975 else:
1976 # almost always empty
1977 attr_list = []
1978
1979 # ... followed by attributes in URI+name order
1980 if attrs:
1981 for k, v in sorted(attrs.items()):
1982 if qattrs is not None and k in qattrs and v in resolved_names:
1983 v = parsed_qnames[resolved_names[v]][0]
1984 attr_qname, attr_name, uri = parsed_qnames[k]
1985 # No prefix for attributes in default ('') namespace.
1986 attr_list.append((attr_qname if uri else attr_name, v))
1987
1988 # Honour xml:space attributes.
1989 space_behaviour = attrs.get('{http://www.w3.org/XML/1998/namespace}space')
1990 self._preserve_space.append(
1991 space_behaviour == 'preserve' if space_behaviour
1992 else self._preserve_space[-1])
1993
1994 # Write the tag.
1995 write = self._write
1996 write('<' + parsed_qnames[tag][0])
1997 if attr_list:
1998 write(''.join([f' {k}="{_escape_attrib_c14n(v)}"' for k, v in attr_list]))
1999 write('>')
2000
2001 # Write the resolved qname text content.
2002 if qname_text is not None:
2003 write(_escape_cdata_c14n(parsed_qnames[resolved_names[qname_text]][0]))
2004
2005 self._root_seen = True
2006 self._ns_stack.append([])
2007
2008 def end(self, tag):
2009 if self._ignored_depth:
2010 self._ignored_depth -= 1
2011 return
2012 if self._data:
2013 self._flush()
2014 self._write(f'</{self._qname(tag)[0]}>')
2015 self._preserve_space.pop()
2016 self._root_done = len(self._preserve_space) == 1
2017 self._declared_ns_stack.pop()
2018 self._ns_stack.pop()
2019
2020 def comment(self, text):
2021 if not self._with_comments:
2022 return
2023 if self._ignored_depth:
2024 return
2025 if self._root_done:
2026 self._write('\n')
2027 elif self._root_seen and self._data:
2028 self._flush()
2029 self._write(f'<!--{_escape_cdata_c14n(text)}-->')
2030 if not self._root_seen:
2031 self._write('\n')
2032
2033 def pi(self, target, data):
2034 if self._ignored_depth:
2035 return
2036 if self._root_done:
2037 self._write('\n')
2038 elif self._root_seen and self._data:
2039 self._flush()
2040 self._write(
2041 f'<?{target} {_escape_cdata_c14n(data)}?>' if data else f'<?{target}?>')
2042 if not self._root_seen:
2043 self._write('\n')
2044
2045
2046 def _escape_cdata_c14n(text):
2047 # escape character data
2048 try:
2049 # it's worth avoiding do-nothing calls for strings that are
2050 # shorter than 500 character, or so. assume that's, by far,
2051 # the most common case in most applications.
2052 if '&' in text:
2053 text = text.replace('&', '&amp;')
2054 if '<' in text:
2055 text = text.replace('<', '&lt;')
2056 if '>' in text:
2057 text = text.replace('>', '&gt;')
2058 if '\r' in text:
2059 text = text.replace('\r', '&#xD;')
2060 return text
2061 except (TypeError, AttributeError):
2062 _raise_serialization_error(text)
2063
2064
2065 def _escape_attrib_c14n(text):
2066 # escape attribute value
2067 try:
2068 if '&' in text:
2069 text = text.replace('&', '&amp;')
2070 if '<' in text:
2071 text = text.replace('<', '&lt;')
2072 if '"' in text:
2073 text = text.replace('"', '&quot;')
2074 if '\t' in text:
2075 text = text.replace('\t', '&#x9;')
2076 if '\n' in text:
2077 text = text.replace('\n', '&#xA;')
2078 if '\r' in text:
2079 text = text.replace('\r', '&#xD;')
2080 return text
2081 except (TypeError, AttributeError):
2082 _raise_serialization_error(text)
2083
2084
2085 # --------------------------------------------------------------------
2086
2087 # Import the C accelerators
2088 try:
2089 # Element is going to be shadowed by the C implementation. We need to keep
2090 # the Python version of it accessible for some "creative" by external code
2091 # (see tests)
2092 _Element_Py = Element
2093
2094 # Element, SubElement, ParseError, TreeBuilder, XMLParser, _set_factories
2095 from _elementtree import *
2096 from _elementtree import _set_factories
2097 except ImportError:
2098 pass
2099 else:
2100 _set_factories(Comment, ProcessingInstruction)