Debian Codegraph @

Lib/xml/etree/ElementTree.py

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