lxml 5.3.0__cp313-cp313-musllinux_1_2_s390x.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. lxml/ElementInclude.py +244 -0
  2. lxml/__init__.py +22 -0
  3. lxml/_elementpath.cpython-313-s390x-linux-musl.so +0 -0
  4. lxml/_elementpath.py +341 -0
  5. lxml/apihelpers.pxi +1793 -0
  6. lxml/builder.cpython-313-s390x-linux-musl.so +0 -0
  7. lxml/builder.py +232 -0
  8. lxml/classlookup.pxi +580 -0
  9. lxml/cleanup.pxi +215 -0
  10. lxml/cssselect.py +101 -0
  11. lxml/debug.pxi +90 -0
  12. lxml/docloader.pxi +178 -0
  13. lxml/doctestcompare.py +488 -0
  14. lxml/dtd.pxi +478 -0
  15. lxml/etree.cpython-313-s390x-linux-musl.so +0 -0
  16. lxml/etree.h +248 -0
  17. lxml/etree.pyx +3731 -0
  18. lxml/etree_api.h +195 -0
  19. lxml/extensions.pxi +833 -0
  20. lxml/html/ElementSoup.py +10 -0
  21. lxml/html/__init__.py +1923 -0
  22. lxml/html/_diffcommand.py +86 -0
  23. lxml/html/_html5builder.py +100 -0
  24. lxml/html/_setmixin.py +56 -0
  25. lxml/html/builder.py +133 -0
  26. lxml/html/clean.py +21 -0
  27. lxml/html/defs.py +135 -0
  28. lxml/html/diff.cpython-313-s390x-linux-musl.so +0 -0
  29. lxml/html/diff.py +878 -0
  30. lxml/html/formfill.py +299 -0
  31. lxml/html/html5parser.py +260 -0
  32. lxml/html/soupparser.py +314 -0
  33. lxml/html/usedoctest.py +13 -0
  34. lxml/includes/__init__.pxd +0 -0
  35. lxml/includes/__init__.py +0 -0
  36. lxml/includes/c14n.pxd +25 -0
  37. lxml/includes/config.pxd +3 -0
  38. lxml/includes/dtdvalid.pxd +18 -0
  39. lxml/includes/etree_defs.h +379 -0
  40. lxml/includes/etreepublic.pxd +237 -0
  41. lxml/includes/extlibs/__init__.py +0 -0
  42. lxml/includes/extlibs/libcharset.h +45 -0
  43. lxml/includes/extlibs/localcharset.h +137 -0
  44. lxml/includes/extlibs/zconf.h +543 -0
  45. lxml/includes/extlibs/zlib.h +1938 -0
  46. lxml/includes/htmlparser.pxd +56 -0
  47. lxml/includes/libexslt/__init__.py +0 -0
  48. lxml/includes/libexslt/exslt.h +108 -0
  49. lxml/includes/libexslt/exsltconfig.h +70 -0
  50. lxml/includes/libexslt/exsltexports.h +63 -0
  51. lxml/includes/libxml/HTMLparser.h +343 -0
  52. lxml/includes/libxml/HTMLtree.h +147 -0
  53. lxml/includes/libxml/SAX.h +202 -0
  54. lxml/includes/libxml/SAX2.h +171 -0
  55. lxml/includes/libxml/__init__.py +0 -0
  56. lxml/includes/libxml/c14n.h +126 -0
  57. lxml/includes/libxml/catalog.h +182 -0
  58. lxml/includes/libxml/chvalid.h +230 -0
  59. lxml/includes/libxml/debugXML.h +217 -0
  60. lxml/includes/libxml/dict.h +82 -0
  61. lxml/includes/libxml/encoding.h +235 -0
  62. lxml/includes/libxml/entities.h +155 -0
  63. lxml/includes/libxml/globals.h +41 -0
  64. lxml/includes/libxml/hash.h +232 -0
  65. lxml/includes/libxml/list.h +137 -0
  66. lxml/includes/libxml/nanoftp.h +186 -0
  67. lxml/includes/libxml/nanohttp.h +81 -0
  68. lxml/includes/libxml/parser.h +1384 -0
  69. lxml/includes/libxml/parserInternals.h +663 -0
  70. lxml/includes/libxml/relaxng.h +219 -0
  71. lxml/includes/libxml/schemasInternals.h +959 -0
  72. lxml/includes/libxml/schematron.h +143 -0
  73. lxml/includes/libxml/threads.h +87 -0
  74. lxml/includes/libxml/tree.h +1362 -0
  75. lxml/includes/libxml/uri.h +95 -0
  76. lxml/includes/libxml/valid.h +450 -0
  77. lxml/includes/libxml/xinclude.h +129 -0
  78. lxml/includes/libxml/xlink.h +189 -0
  79. lxml/includes/libxml/xmlIO.h +421 -0
  80. lxml/includes/libxml/xmlautomata.h +146 -0
  81. lxml/includes/libxml/xmlerror.h +948 -0
  82. lxml/includes/libxml/xmlexports.h +50 -0
  83. lxml/includes/libxml/xmlmemory.h +225 -0
  84. lxml/includes/libxml/xmlmodule.h +57 -0
  85. lxml/includes/libxml/xmlreader.h +434 -0
  86. lxml/includes/libxml/xmlregexp.h +215 -0
  87. lxml/includes/libxml/xmlsave.h +97 -0
  88. lxml/includes/libxml/xmlschemas.h +249 -0
  89. lxml/includes/libxml/xmlschemastypes.h +152 -0
  90. lxml/includes/libxml/xmlstring.h +140 -0
  91. lxml/includes/libxml/xmlunicode.h +202 -0
  92. lxml/includes/libxml/xmlversion.h +511 -0
  93. lxml/includes/libxml/xmlwriter.h +488 -0
  94. lxml/includes/libxml/xpath.h +575 -0
  95. lxml/includes/libxml/xpathInternals.h +633 -0
  96. lxml/includes/libxml/xpointer.h +138 -0
  97. lxml/includes/libxslt/__init__.py +0 -0
  98. lxml/includes/libxslt/attributes.h +39 -0
  99. lxml/includes/libxslt/documents.h +93 -0
  100. lxml/includes/libxslt/extensions.h +262 -0
  101. lxml/includes/libxslt/extra.h +72 -0
  102. lxml/includes/libxslt/functions.h +78 -0
  103. lxml/includes/libxslt/imports.h +75 -0
  104. lxml/includes/libxslt/keys.h +53 -0
  105. lxml/includes/libxslt/namespaces.h +68 -0
  106. lxml/includes/libxslt/numbersInternals.h +73 -0
  107. lxml/includes/libxslt/pattern.h +84 -0
  108. lxml/includes/libxslt/preproc.h +43 -0
  109. lxml/includes/libxslt/security.h +104 -0
  110. lxml/includes/libxslt/templates.h +77 -0
  111. lxml/includes/libxslt/transform.h +207 -0
  112. lxml/includes/libxslt/variables.h +118 -0
  113. lxml/includes/libxslt/xslt.h +110 -0
  114. lxml/includes/libxslt/xsltInternals.h +1995 -0
  115. lxml/includes/libxslt/xsltconfig.h +146 -0
  116. lxml/includes/libxslt/xsltexports.h +64 -0
  117. lxml/includes/libxslt/xsltlocale.h +44 -0
  118. lxml/includes/libxslt/xsltutils.h +343 -0
  119. lxml/includes/lxml-version.h +3 -0
  120. lxml/includes/relaxng.pxd +64 -0
  121. lxml/includes/schematron.pxd +34 -0
  122. lxml/includes/tree.pxd +494 -0
  123. lxml/includes/uri.pxd +5 -0
  124. lxml/includes/xinclude.pxd +22 -0
  125. lxml/includes/xmlerror.pxd +852 -0
  126. lxml/includes/xmlparser.pxd +265 -0
  127. lxml/includes/xmlschema.pxd +35 -0
  128. lxml/includes/xpath.pxd +136 -0
  129. lxml/includes/xslt.pxd +190 -0
  130. lxml/isoschematron/__init__.py +348 -0
  131. lxml/isoschematron/resources/rng/iso-schematron.rng +709 -0
  132. lxml/isoschematron/resources/xsl/RNG2Schtrn.xsl +75 -0
  133. lxml/isoschematron/resources/xsl/XSD2Schtrn.xsl +77 -0
  134. lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_abstract_expand.xsl +313 -0
  135. lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_dsdl_include.xsl +1160 -0
  136. lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_message.xsl +55 -0
  137. lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_skeleton_for_xslt1.xsl +1796 -0
  138. lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_svrl_for_xslt1.xsl +588 -0
  139. lxml/isoschematron/resources/xsl/iso-schematron-xslt1/readme.txt +84 -0
  140. lxml/iterparse.pxi +438 -0
  141. lxml/lxml.etree.h +248 -0
  142. lxml/lxml.etree_api.h +195 -0
  143. lxml/nsclasses.pxi +281 -0
  144. lxml/objectify.cpython-313-s390x-linux-musl.so +0 -0
  145. lxml/objectify.pyx +2145 -0
  146. lxml/objectpath.pxi +332 -0
  147. lxml/parser.pxi +2000 -0
  148. lxml/parsertarget.pxi +180 -0
  149. lxml/proxy.pxi +619 -0
  150. lxml/public-api.pxi +178 -0
  151. lxml/pyclasslookup.py +3 -0
  152. lxml/readonlytree.pxi +565 -0
  153. lxml/relaxng.pxi +165 -0
  154. lxml/sax.cpython-313-s390x-linux-musl.so +0 -0
  155. lxml/sax.py +275 -0
  156. lxml/saxparser.pxi +875 -0
  157. lxml/schematron.pxi +168 -0
  158. lxml/serializer.pxi +1781 -0
  159. lxml/usedoctest.py +13 -0
  160. lxml/xinclude.pxi +67 -0
  161. lxml/xmlerror.pxi +1654 -0
  162. lxml/xmlid.pxi +179 -0
  163. lxml/xmlschema.pxi +215 -0
  164. lxml/xpath.pxi +487 -0
  165. lxml/xslt.pxi +950 -0
  166. lxml/xsltext.pxi +242 -0
  167. lxml-5.3.0.dist-info/LICENSE.txt +29 -0
  168. lxml-5.3.0.dist-info/LICENSES.txt +29 -0
  169. lxml-5.3.0.dist-info/METADATA +103 -0
  170. lxml-5.3.0.dist-info/RECORD +172 -0
  171. lxml-5.3.0.dist-info/WHEEL +5 -0
  172. lxml-5.3.0.dist-info/top_level.txt +1 -0
lxml/etree.pyx ADDED
@@ -0,0 +1,3731 @@
1
+ # cython: binding=True
2
+ # cython: auto_pickle=False
3
+ # cython: language_level=3
4
+
5
+ """
6
+ The ``lxml.etree`` module implements the extended ElementTree API for XML.
7
+ """
8
+
9
+ __docformat__ = "restructuredtext en"
10
+
11
+ __all__ = [
12
+ 'AttributeBasedElementClassLookup', 'C14NError', 'C14NWriterTarget', 'CDATA',
13
+ 'Comment', 'CommentBase', 'CustomElementClassLookup', 'DEBUG',
14
+ 'DTD', 'DTDError', 'DTDParseError', 'DTDValidateError',
15
+ 'DocumentInvalid', 'ETCompatXMLParser', 'ETXPath', 'Element',
16
+ 'ElementBase', 'ElementClassLookup', 'ElementDefaultClassLookup',
17
+ 'ElementNamespaceClassLookup', 'ElementTree', 'Entity', 'EntityBase',
18
+ 'Error', 'ErrorDomains', 'ErrorLevels', 'ErrorTypes', 'Extension',
19
+ 'FallbackElementClassLookup', 'FunctionNamespace', 'HTML', 'HTMLParser',
20
+ 'ICONV_COMPILED_VERSION',
21
+ 'LIBXML_COMPILED_VERSION', 'LIBXML_VERSION',
22
+ 'LIBXSLT_COMPILED_VERSION', 'LIBXSLT_VERSION',
23
+ 'LXML_VERSION',
24
+ 'LxmlError', 'LxmlRegistryError', 'LxmlSyntaxError',
25
+ 'NamespaceRegistryError', 'PI', 'PIBase', 'ParseError',
26
+ 'ParserBasedElementClassLookup', 'ParserError', 'ProcessingInstruction',
27
+ 'PyErrorLog', 'PythonElementClassLookup', 'QName', 'RelaxNG',
28
+ 'RelaxNGError', 'RelaxNGErrorTypes', 'RelaxNGParseError',
29
+ 'RelaxNGValidateError', 'Resolver', 'Schematron', 'SchematronError',
30
+ 'SchematronParseError', 'SchematronValidateError', 'SerialisationError',
31
+ 'SubElement', 'TreeBuilder', 'XInclude', 'XIncludeError', 'XML',
32
+ 'XMLDTDID', 'XMLID', 'XMLParser', 'XMLSchema', 'XMLSchemaError',
33
+ 'XMLSchemaParseError', 'XMLSchemaValidateError', 'XMLSyntaxError',
34
+ 'XMLTreeBuilder', 'XPath', 'XPathDocumentEvaluator', 'XPathError',
35
+ 'XPathEvalError', 'XPathEvaluator', 'XPathFunctionError', 'XPathResultError',
36
+ 'XPathSyntaxError', 'XSLT', 'XSLTAccessControl', 'XSLTApplyError',
37
+ 'XSLTError', 'XSLTExtension', 'XSLTExtensionError', 'XSLTParseError',
38
+ 'XSLTSaveError', 'canonicalize',
39
+ 'cleanup_namespaces', 'clear_error_log', 'dump',
40
+ 'fromstring', 'fromstringlist', 'get_default_parser', 'iselement',
41
+ 'iterparse', 'iterwalk', 'parse', 'parseid', 'register_namespace',
42
+ 'set_default_parser', 'set_element_class_lookup', 'strip_attributes',
43
+ 'strip_elements', 'strip_tags', 'tostring', 'tostringlist', 'tounicode',
44
+ 'use_global_python_log'
45
+ ]
46
+
47
+ cimport cython
48
+
49
+ from lxml cimport python
50
+ from lxml.includes cimport tree, config
51
+ from lxml.includes.tree cimport xmlDoc, xmlNode, xmlAttr, xmlNs, _isElement, _getNs
52
+ from lxml.includes.tree cimport const_xmlChar, xmlChar, _xcstr
53
+ from lxml.python cimport _cstr, _isString
54
+ from lxml.includes cimport xpath
55
+ from lxml.includes cimport c14n
56
+
57
+ # Cython's standard declarations
58
+ cimport cpython.mem
59
+ cimport cpython.ref
60
+ from libc cimport limits, stdio, stdlib
61
+ from libc cimport string as cstring_h # not to be confused with stdlib 'string'
62
+ from libc.string cimport const_char
63
+
64
+ cdef object os_path_abspath
65
+ from os.path import abspath as os_path_abspath
66
+
67
+ cdef object BytesIO, StringIO
68
+ from io import BytesIO, StringIO
69
+
70
+ cdef object OrderedDict
71
+ from collections import OrderedDict
72
+
73
+ cdef object _elementpath
74
+ from lxml import _elementpath
75
+
76
+ cdef object sys
77
+ import sys
78
+
79
+ cdef object re
80
+ import re
81
+
82
+ cdef object partial
83
+ from functools import partial
84
+
85
+ cdef object islice
86
+ from itertools import islice
87
+
88
+ cdef object ITER_EMPTY = iter(())
89
+
90
+ cdef object MutableMapping
91
+ from collections.abc import MutableMapping
92
+
93
+ class _ImmutableMapping(MutableMapping):
94
+ def __getitem__(self, key):
95
+ raise KeyError, key
96
+
97
+ def __setitem__(self, key, value):
98
+ raise KeyError, key
99
+
100
+ def __delitem__(self, key):
101
+ raise KeyError, key
102
+
103
+ def __contains__(self, key):
104
+ return False
105
+
106
+ def __len__(self):
107
+ return 0
108
+
109
+ def __iter__(self):
110
+ return ITER_EMPTY
111
+ iterkeys = itervalues = iteritems = __iter__
112
+
113
+ cdef object IMMUTABLE_EMPTY_MAPPING = _ImmutableMapping()
114
+ del _ImmutableMapping
115
+
116
+
117
+ # the rules
118
+ # ---------
119
+ # any libxml C argument/variable is prefixed with c_
120
+ # any non-public function/class is prefixed with an underscore
121
+ # instance creation is always through factories
122
+
123
+ # what to do with libxml2/libxslt error messages?
124
+ # 0 : drop
125
+ # 1 : use log
126
+ DEF __DEBUG = 1
127
+
128
+ # maximum number of lines in the libxml2/xslt log if __DEBUG == 1
129
+ DEF __MAX_LOG_SIZE = 100
130
+
131
+ # make the compiled-in debug state publicly available
132
+ DEBUG = __DEBUG
133
+
134
+ # A struct to store a cached qualified tag name+href pair.
135
+ # While we can borrow the c_name from the document dict,
136
+ # PyPy requires us to store a Python reference for the
137
+ # namespace in order to keep the byte buffer alive.
138
+ cdef struct qname:
139
+ const_xmlChar* c_name
140
+ python.PyObject* href
141
+
142
+ # initialize parser (and threading)
143
+ xmlparser.xmlInitParser()
144
+
145
+ # global per-thread setup
146
+ tree.xmlThrDefIndentTreeOutput(1)
147
+ tree.xmlThrDefLineNumbersDefaultValue(1)
148
+
149
+ _initThreadLogging()
150
+
151
+ # filename encoding
152
+ cdef bytes _FILENAME_ENCODING = (sys.getfilesystemencoding() or sys.getdefaultencoding() or 'ascii').encode("UTF-8")
153
+ cdef char* _C_FILENAME_ENCODING = _cstr(_FILENAME_ENCODING)
154
+
155
+ # set up some default namespace prefixes
156
+ cdef dict _DEFAULT_NAMESPACE_PREFIXES = {
157
+ b"http://www.w3.org/XML/1998/namespace": b'xml',
158
+ b"http://www.w3.org/1999/xhtml": b"html",
159
+ b"http://www.w3.org/1999/XSL/Transform": b"xsl",
160
+ b"http://www.w3.org/1999/02/22-rdf-syntax-ns#": b"rdf",
161
+ b"http://schemas.xmlsoap.org/wsdl/": b"wsdl",
162
+ # xml schema
163
+ b"http://www.w3.org/2001/XMLSchema": b"xs",
164
+ b"http://www.w3.org/2001/XMLSchema-instance": b"xsi",
165
+ # dublin core
166
+ b"http://purl.org/dc/elements/1.1/": b"dc",
167
+ # objectify
168
+ b"http://codespeak.net/lxml/objectify/pytype" : b"py",
169
+ }
170
+
171
+ # To avoid runtime encoding overhead, we keep a Unicode copy
172
+ # of the uri-prefix mapping as (str, str) items view.
173
+ cdef object _DEFAULT_NAMESPACE_PREFIXES_ITEMS = []
174
+
175
+ cdef _update_default_namespace_prefixes_items():
176
+ cdef bytes ns, prefix
177
+ global _DEFAULT_NAMESPACE_PREFIXES_ITEMS
178
+ _DEFAULT_NAMESPACE_PREFIXES_ITEMS = {
179
+ ns.decode('utf-8') : prefix.decode('utf-8')
180
+ for ns, prefix in _DEFAULT_NAMESPACE_PREFIXES.items()
181
+ }.items()
182
+
183
+ _update_default_namespace_prefixes_items()
184
+
185
+ cdef object _check_internal_prefix = re.compile(br"ns\d+$").match
186
+
187
+ def register_namespace(prefix, uri):
188
+ """Registers a namespace prefix that newly created Elements in that
189
+ namespace will use. The registry is global, and any existing
190
+ mapping for either the given prefix or the namespace URI will be
191
+ removed.
192
+ """
193
+ prefix_utf, uri_utf = _utf8(prefix), _utf8(uri)
194
+ if _check_internal_prefix(prefix_utf):
195
+ raise ValueError("Prefix format reserved for internal use")
196
+ _tagValidOrRaise(prefix_utf)
197
+ _uriValidOrRaise(uri_utf)
198
+ if (uri_utf == b"http://www.w3.org/XML/1998/namespace" and prefix_utf != b'xml'
199
+ or prefix_utf == b'xml' and uri_utf != b"http://www.w3.org/XML/1998/namespace"):
200
+ raise ValueError("Cannot change the 'xml' prefix of the XML namespace")
201
+ for k, v in list(_DEFAULT_NAMESPACE_PREFIXES.items()):
202
+ if k == uri_utf or v == prefix_utf:
203
+ del _DEFAULT_NAMESPACE_PREFIXES[k]
204
+ _DEFAULT_NAMESPACE_PREFIXES[uri_utf] = prefix_utf
205
+ _update_default_namespace_prefixes_items()
206
+
207
+
208
+ # Error superclass for ElementTree compatibility
209
+ cdef class Error(Exception):
210
+ pass
211
+
212
+ # module level superclass for all exceptions
213
+ cdef class LxmlError(Error):
214
+ """Main exception base class for lxml. All other exceptions inherit from
215
+ this one.
216
+ """
217
+ def __init__(self, message, error_log=None):
218
+ super(_Error, self).__init__(message)
219
+ if error_log is None:
220
+ self.error_log = __copyGlobalErrorLog()
221
+ else:
222
+ self.error_log = error_log.copy()
223
+
224
+ cdef object _Error = Error
225
+
226
+
227
+ # superclass for all syntax errors
228
+ class LxmlSyntaxError(LxmlError, SyntaxError):
229
+ """Base class for all syntax errors.
230
+ """
231
+
232
+ cdef class C14NError(LxmlError):
233
+ """Error during C14N serialisation.
234
+ """
235
+
236
+ # version information
237
+ cdef tuple __unpackDottedVersion(version):
238
+ version_list = []
239
+ l = (version.decode("ascii").replace('-', '.').split('.') + [0]*4)[:4]
240
+ for item in l:
241
+ try:
242
+ item = int(item)
243
+ except ValueError:
244
+ if item.startswith('dev'):
245
+ count = item[3:]
246
+ item = -300
247
+ elif item.startswith('alpha'):
248
+ count = item[5:]
249
+ item = -200
250
+ elif item.startswith('beta'):
251
+ count = item[4:]
252
+ item = -100
253
+ else:
254
+ count = 0
255
+ if count:
256
+ item += int(count)
257
+ version_list.append(item)
258
+ return tuple(version_list)
259
+
260
+ cdef tuple __unpackIntVersion(int c_version, int base=100):
261
+ return (
262
+ ((c_version // (base*base)) % base),
263
+ ((c_version // base) % base),
264
+ (c_version % base)
265
+ )
266
+
267
+ cdef int _LIBXML_VERSION_INT
268
+ try:
269
+ _LIBXML_VERSION_INT = int(
270
+ re.match('[0-9]+', (<unsigned char*>tree.xmlParserVersion).decode("ascii")).group(0))
271
+ except Exception:
272
+ print("Unknown libxml2 version: " + (<unsigned char*>tree.xmlParserVersion).decode("latin1"))
273
+ _LIBXML_VERSION_INT = 0
274
+
275
+ LIBXML_VERSION = __unpackIntVersion(_LIBXML_VERSION_INT)
276
+ LIBXML_COMPILED_VERSION = __unpackIntVersion(tree.LIBXML_VERSION)
277
+ LXML_VERSION = __unpackDottedVersion(tree.LXML_VERSION_STRING)
278
+
279
+ __version__ = tree.LXML_VERSION_STRING.decode("ascii")
280
+
281
+ cdef extern from *:
282
+ """
283
+ #ifdef ZLIB_VERNUM
284
+ #define __lxml_zlib_version (ZLIB_VERNUM >> 4)
285
+ #else
286
+ #define __lxml_zlib_version 0
287
+ #endif
288
+ #ifdef _LIBICONV_VERSION
289
+ #define __lxml_iconv_version (_LIBICONV_VERSION << 8)
290
+ #else
291
+ #define __lxml_iconv_version 0
292
+ #endif
293
+ """
294
+ # zlib isn't included automatically by libxml2's headers
295
+ #long ZLIB_HEX_VERSION "__lxml_zlib_version"
296
+ long LIBICONV_HEX_VERSION "__lxml_iconv_version"
297
+
298
+ #ZLIB_COMPILED_VERSION = __unpackIntVersion(ZLIB_HEX_VERSION, base=0x10)
299
+ ICONV_COMPILED_VERSION = __unpackIntVersion(LIBICONV_HEX_VERSION, base=0x100)[:2]
300
+
301
+
302
+ # class for temporary storage of Python references,
303
+ # used e.g. for XPath results
304
+ @cython.final
305
+ @cython.internal
306
+ cdef class _TempStore:
307
+ cdef list _storage
308
+ def __init__(self):
309
+ self._storage = []
310
+
311
+ cdef int add(self, obj) except -1:
312
+ self._storage.append(obj)
313
+ return 0
314
+
315
+ cdef int clear(self) except -1:
316
+ del self._storage[:]
317
+ return 0
318
+
319
+
320
+ # class for temporarily storing exceptions raised in extensions
321
+ @cython.internal
322
+ cdef class _ExceptionContext:
323
+ cdef object _exc_info
324
+ cdef int clear(self) except -1:
325
+ self._exc_info = None
326
+ return 0
327
+
328
+ cdef void _store_raised(self) noexcept:
329
+ try:
330
+ self._exc_info = sys.exc_info()
331
+ except BaseException as e:
332
+ self._store_exception(e)
333
+ finally:
334
+ return # and swallow any further exceptions
335
+
336
+ cdef int _store_exception(self, exception) except -1:
337
+ self._exc_info = (exception, None, None)
338
+ return 0
339
+
340
+ cdef bint _has_raised(self) except -1:
341
+ return self._exc_info is not None
342
+
343
+ cdef int _raise_if_stored(self) except -1:
344
+ if self._exc_info is None:
345
+ return 0
346
+ type, value, traceback = self._exc_info
347
+ self._exc_info = None
348
+ if value is None and traceback is None:
349
+ raise type
350
+ else:
351
+ raise type, value, traceback
352
+
353
+
354
+ # type of a function that steps from node to node
355
+ ctypedef public xmlNode* (*_node_to_node_function)(xmlNode*)
356
+
357
+
358
+ ################################################################################
359
+ # Include submodules
360
+
361
+ include "proxy.pxi" # Proxy handling (element backpointers/memory/etc.)
362
+ include "apihelpers.pxi" # Private helper functions
363
+ include "xmlerror.pxi" # Error and log handling
364
+
365
+
366
+ ################################################################################
367
+ # Public Python API
368
+
369
+ @cython.final
370
+ @cython.freelist(8)
371
+ cdef public class _Document [ type LxmlDocumentType, object LxmlDocument ]:
372
+ """Internal base class to reference a libxml document.
373
+
374
+ When instances of this class are garbage collected, the libxml
375
+ document is cleaned up.
376
+ """
377
+ cdef int _ns_counter
378
+ cdef bytes _prefix_tail
379
+ cdef xmlDoc* _c_doc
380
+ cdef _BaseParser _parser
381
+
382
+ def __dealloc__(self):
383
+ # if there are no more references to the document, it is safe
384
+ # to clean the whole thing up, as all nodes have a reference to
385
+ # the document
386
+ tree.xmlFreeDoc(self._c_doc)
387
+
388
+ @cython.final
389
+ cdef getroot(self):
390
+ # return an element proxy for the document root
391
+ cdef xmlNode* c_node
392
+ c_node = tree.xmlDocGetRootElement(self._c_doc)
393
+ if c_node is NULL:
394
+ return None
395
+ return _elementFactory(self, c_node)
396
+
397
+ @cython.final
398
+ cdef bint hasdoctype(self) noexcept:
399
+ # DOCTYPE gets parsed into internal subset (xmlDTD*)
400
+ return self._c_doc is not NULL and self._c_doc.intSubset is not NULL
401
+
402
+ @cython.final
403
+ cdef getdoctype(self):
404
+ # get doctype info: root tag, public/system ID (or None if not known)
405
+ cdef tree.xmlDtd* c_dtd
406
+ cdef xmlNode* c_root_node
407
+ public_id = None
408
+ sys_url = None
409
+ c_dtd = self._c_doc.intSubset
410
+ if c_dtd is not NULL:
411
+ if c_dtd.ExternalID is not NULL:
412
+ public_id = funicode(c_dtd.ExternalID)
413
+ if c_dtd.SystemID is not NULL:
414
+ sys_url = funicode(c_dtd.SystemID)
415
+ c_dtd = self._c_doc.extSubset
416
+ if c_dtd is not NULL:
417
+ if not public_id and c_dtd.ExternalID is not NULL:
418
+ public_id = funicode(c_dtd.ExternalID)
419
+ if not sys_url and c_dtd.SystemID is not NULL:
420
+ sys_url = funicode(c_dtd.SystemID)
421
+ c_root_node = tree.xmlDocGetRootElement(self._c_doc)
422
+ if c_root_node is NULL:
423
+ root_name = None
424
+ else:
425
+ root_name = funicode(c_root_node.name)
426
+ return root_name, public_id, sys_url
427
+
428
+ @cython.final
429
+ cdef getxmlinfo(self):
430
+ # return XML version and encoding (or None if not known)
431
+ cdef xmlDoc* c_doc = self._c_doc
432
+ if c_doc.version is NULL:
433
+ version = None
434
+ else:
435
+ version = funicode(c_doc.version)
436
+ if c_doc.encoding is NULL:
437
+ encoding = None
438
+ else:
439
+ encoding = funicode(c_doc.encoding)
440
+ return version, encoding
441
+
442
+ @cython.final
443
+ cdef isstandalone(self):
444
+ # returns True for "standalone=true",
445
+ # False for "standalone=false", None if not provided
446
+ if self._c_doc.standalone == -1:
447
+ return None
448
+ else:
449
+ return <bint>(self._c_doc.standalone == 1)
450
+
451
+ @cython.final
452
+ cdef bytes buildNewPrefix(self):
453
+ # get a new unique prefix ("nsX") for this document
454
+ cdef bytes ns
455
+ if self._ns_counter < len(_PREFIX_CACHE):
456
+ ns = _PREFIX_CACHE[self._ns_counter]
457
+ else:
458
+ ns = python.PyBytes_FromFormat("ns%d", self._ns_counter)
459
+ if self._prefix_tail is not None:
460
+ ns += self._prefix_tail
461
+ self._ns_counter += 1
462
+ if self._ns_counter < 0:
463
+ # overflow!
464
+ self._ns_counter = 0
465
+ if self._prefix_tail is None:
466
+ self._prefix_tail = b"A"
467
+ else:
468
+ self._prefix_tail += b"A"
469
+ return ns
470
+
471
+ @cython.final
472
+ cdef xmlNs* _findOrBuildNodeNs(self, xmlNode* c_node,
473
+ const_xmlChar* c_href, const_xmlChar* c_prefix,
474
+ bint is_attribute) except NULL:
475
+ """Get or create namespace structure for a node. Reuses the prefix if
476
+ possible.
477
+ """
478
+ cdef xmlNs* c_ns
479
+ cdef xmlNs* c_doc_ns
480
+ cdef python.PyObject* dict_result
481
+ if c_node.type != tree.XML_ELEMENT_NODE:
482
+ assert c_node.type == tree.XML_ELEMENT_NODE, \
483
+ "invalid node type %d, expected %d" % (
484
+ c_node.type, tree.XML_ELEMENT_NODE)
485
+ # look for existing ns declaration
486
+ c_ns = _searchNsByHref(c_node, c_href, is_attribute)
487
+ if c_ns is not NULL:
488
+ if is_attribute and c_ns.prefix is NULL:
489
+ # do not put namespaced attributes into the default
490
+ # namespace as this would break serialisation
491
+ pass
492
+ else:
493
+ return c_ns
494
+
495
+ # none found => determine a suitable new prefix
496
+ if c_prefix is NULL:
497
+ dict_result = python.PyDict_GetItem(
498
+ _DEFAULT_NAMESPACE_PREFIXES, <unsigned char*>c_href)
499
+ if dict_result is not NULL:
500
+ prefix = <object>dict_result
501
+ else:
502
+ prefix = self.buildNewPrefix()
503
+ c_prefix = _xcstr(prefix)
504
+
505
+ # make sure the prefix is not in use already
506
+ while tree.xmlSearchNs(self._c_doc, c_node, c_prefix) is not NULL:
507
+ prefix = self.buildNewPrefix()
508
+ c_prefix = _xcstr(prefix)
509
+
510
+ # declare the namespace and return it
511
+ c_ns = tree.xmlNewNs(c_node, c_href, c_prefix)
512
+ if c_ns is NULL:
513
+ raise MemoryError()
514
+ return c_ns
515
+
516
+ @cython.final
517
+ cdef int _setNodeNs(self, xmlNode* c_node, const_xmlChar* c_href) except -1:
518
+ "Lookup namespace structure and set it for the node."
519
+ c_ns = self._findOrBuildNodeNs(c_node, c_href, NULL, 0)
520
+ tree.xmlSetNs(c_node, c_ns)
521
+
522
+ cdef tuple __initPrefixCache():
523
+ cdef int i
524
+ return tuple([ python.PyBytes_FromFormat("ns%d", i)
525
+ for i in range(30) ])
526
+
527
+ cdef tuple _PREFIX_CACHE = __initPrefixCache()
528
+
529
+ cdef _Document _documentFactory(xmlDoc* c_doc, _BaseParser parser):
530
+ cdef _Document result
531
+ result = _Document.__new__(_Document)
532
+ result._c_doc = c_doc
533
+ result._ns_counter = 0
534
+ result._prefix_tail = None
535
+ if parser is None:
536
+ parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
537
+ result._parser = parser
538
+ return result
539
+
540
+
541
+ cdef object _find_invalid_public_id_characters = re.compile(
542
+ ur"[^\x20\x0D\x0Aa-zA-Z0-9'()+,./:=?;!*#@$_%-]+").search
543
+
544
+
545
+ cdef class DocInfo:
546
+ "Document information provided by parser and DTD."
547
+ cdef _Document _doc
548
+ def __cinit__(self, tree):
549
+ "Create a DocInfo object for an ElementTree object or root Element."
550
+ self._doc = _documentOrRaise(tree)
551
+ root_name, public_id, system_url = self._doc.getdoctype()
552
+ if not root_name and (public_id or system_url):
553
+ raise ValueError, "Could not find root node"
554
+
555
+ @property
556
+ def root_name(self):
557
+ """Returns the name of the root node as defined by the DOCTYPE."""
558
+ root_name, public_id, system_url = self._doc.getdoctype()
559
+ return root_name
560
+
561
+ @cython.final
562
+ cdef tree.xmlDtd* _get_c_dtd(self):
563
+ """"Return the DTD. Create it if it does not yet exist."""
564
+ cdef xmlDoc* c_doc = self._doc._c_doc
565
+ cdef xmlNode* c_root_node
566
+ cdef const_xmlChar* c_name
567
+
568
+ if c_doc.intSubset:
569
+ return c_doc.intSubset
570
+
571
+ c_root_node = tree.xmlDocGetRootElement(c_doc)
572
+ c_name = c_root_node.name if c_root_node else NULL
573
+ return tree.xmlCreateIntSubset(c_doc, c_name, NULL, NULL)
574
+
575
+ def clear(self):
576
+ """Removes DOCTYPE and internal subset from the document."""
577
+ cdef xmlDoc* c_doc = self._doc._c_doc
578
+ cdef tree.xmlNode* c_dtd = <xmlNode*>c_doc.intSubset
579
+ if c_dtd is NULL:
580
+ return
581
+ tree.xmlUnlinkNode(c_dtd)
582
+ tree.xmlFreeNode(c_dtd)
583
+
584
+ property public_id:
585
+ """Public ID of the DOCTYPE.
586
+
587
+ Mutable. May be set to a valid string or None. If a DTD does not
588
+ exist, setting this variable (even to None) will create one.
589
+ """
590
+ def __get__(self):
591
+ root_name, public_id, system_url = self._doc.getdoctype()
592
+ return public_id
593
+
594
+ def __set__(self, value):
595
+ cdef xmlChar* c_value = NULL
596
+ if value is not None:
597
+ match = _find_invalid_public_id_characters(value)
598
+ if match:
599
+ raise ValueError, f'Invalid character(s) {match.group(0)!r} in public_id.'
600
+ value = _utf8(value)
601
+ c_value = tree.xmlStrdup(_xcstr(value))
602
+ if not c_value:
603
+ raise MemoryError()
604
+
605
+ c_dtd = self._get_c_dtd()
606
+ if not c_dtd:
607
+ tree.xmlFree(c_value)
608
+ raise MemoryError()
609
+ if c_dtd.ExternalID:
610
+ tree.xmlFree(<void*>c_dtd.ExternalID)
611
+ c_dtd.ExternalID = c_value
612
+
613
+ property system_url:
614
+ """System ID of the DOCTYPE.
615
+
616
+ Mutable. May be set to a valid string or None. If a DTD does not
617
+ exist, setting this variable (even to None) will create one.
618
+ """
619
+ def __get__(self):
620
+ root_name, public_id, system_url = self._doc.getdoctype()
621
+ return system_url
622
+
623
+ def __set__(self, value):
624
+ cdef xmlChar* c_value = NULL
625
+ if value is not None:
626
+ bvalue = _utf8(value)
627
+ # sys_url may be any valid unicode string that can be
628
+ # enclosed in single quotes or quotes.
629
+ if b"'" in bvalue and b'"' in bvalue:
630
+ raise ValueError(
631
+ 'System URL may not contain both single (\') and double quotes (").')
632
+ c_value = tree.xmlStrdup(_xcstr(bvalue))
633
+ if not c_value:
634
+ raise MemoryError()
635
+
636
+ c_dtd = self._get_c_dtd()
637
+ if not c_dtd:
638
+ tree.xmlFree(c_value)
639
+ raise MemoryError()
640
+ if c_dtd.SystemID:
641
+ tree.xmlFree(<void*>c_dtd.SystemID)
642
+ c_dtd.SystemID = c_value
643
+
644
+ @property
645
+ def xml_version(self):
646
+ """Returns the XML version as declared by the document."""
647
+ xml_version, encoding = self._doc.getxmlinfo()
648
+ return xml_version
649
+
650
+ @property
651
+ def encoding(self):
652
+ """Returns the encoding name as declared by the document."""
653
+ xml_version, encoding = self._doc.getxmlinfo()
654
+ return encoding
655
+
656
+ @property
657
+ def standalone(self):
658
+ """Returns the standalone flag as declared by the document. The possible
659
+ values are True (``standalone='yes'``), False
660
+ (``standalone='no'`` or flag not provided in the declaration),
661
+ and None (unknown or no declaration found). Note that a
662
+ normal truth test on this value will always tell if the
663
+ ``standalone`` flag was set to ``'yes'`` or not.
664
+ """
665
+ return self._doc.isstandalone()
666
+
667
+ property URL:
668
+ "The source URL of the document (or None if unknown)."
669
+ def __get__(self):
670
+ if self._doc._c_doc.URL is NULL:
671
+ return None
672
+ return _decodeFilename(self._doc._c_doc.URL)
673
+ def __set__(self, url):
674
+ url = _encodeFilename(url)
675
+ c_oldurl = self._doc._c_doc.URL
676
+ if url is None:
677
+ self._doc._c_doc.URL = NULL
678
+ else:
679
+ self._doc._c_doc.URL = tree.xmlStrdup(_xcstr(url))
680
+ if c_oldurl is not NULL:
681
+ tree.xmlFree(<void*>c_oldurl)
682
+
683
+ @property
684
+ def doctype(self):
685
+ """Returns a DOCTYPE declaration string for the document."""
686
+ root_name, public_id, system_url = self._doc.getdoctype()
687
+ if system_url:
688
+ # If '"' in system_url, we must escape it with single
689
+ # quotes, otherwise escape with double quotes. If url
690
+ # contains both a single quote and a double quote, XML
691
+ # standard is being violated.
692
+ if '"' in system_url:
693
+ quoted_system_url = f"'{system_url}'"
694
+ else:
695
+ quoted_system_url = f'"{system_url}"'
696
+ if public_id:
697
+ if system_url:
698
+ return f'<!DOCTYPE {root_name} PUBLIC "{public_id}" {quoted_system_url}>'
699
+ else:
700
+ return f'<!DOCTYPE {root_name} PUBLIC "{public_id}">'
701
+ elif system_url:
702
+ return f'<!DOCTYPE {root_name} SYSTEM {quoted_system_url}>'
703
+ elif self._doc.hasdoctype():
704
+ return f'<!DOCTYPE {root_name}>'
705
+ else:
706
+ return ''
707
+
708
+ @property
709
+ def internalDTD(self):
710
+ """Returns a DTD validator based on the internal subset of the document."""
711
+ return _dtdFactory(self._doc._c_doc.intSubset)
712
+
713
+ @property
714
+ def externalDTD(self):
715
+ """Returns a DTD validator based on the external subset of the document."""
716
+ return _dtdFactory(self._doc._c_doc.extSubset)
717
+
718
+
719
+ @cython.no_gc_clear
720
+ cdef public class _Element [ type LxmlElementType, object LxmlElement ]:
721
+ """Element class.
722
+
723
+ References a document object and a libxml node.
724
+
725
+ By pointing to a Document instance, a reference is kept to
726
+ _Document as long as there is some pointer to a node in it.
727
+ """
728
+ cdef _Document _doc
729
+ cdef xmlNode* _c_node
730
+ cdef object _tag
731
+
732
+ def _init(self):
733
+ """_init(self)
734
+
735
+ Called after object initialisation. Custom subclasses may override
736
+ this if they recursively call _init() in the superclasses.
737
+ """
738
+
739
+ @cython.linetrace(False)
740
+ @cython.profile(False)
741
+ def __dealloc__(self):
742
+ #print("trying to free node:", <int>self._c_node)
743
+ #displayNode(self._c_node, 0)
744
+ if self._c_node is not NULL:
745
+ _unregisterProxy(self)
746
+ attemptDeallocation(self._c_node)
747
+
748
+ # MANIPULATORS
749
+
750
+ def __setitem__(self, x, value):
751
+ """__setitem__(self, x, value)
752
+
753
+ Replaces the given subelement index or slice.
754
+ """
755
+ cdef xmlNode* c_node = NULL
756
+ cdef xmlNode* c_next
757
+ cdef xmlDoc* c_source_doc
758
+ cdef _Element element
759
+ cdef bint left_to_right
760
+ cdef Py_ssize_t slicelength = 0, step = 0
761
+ _assertValidNode(self)
762
+ if value is None:
763
+ raise ValueError, "cannot assign None"
764
+ if isinstance(x, slice):
765
+ # slice assignment
766
+ _findChildSlice(<slice>x, self._c_node, &c_node, &step, &slicelength)
767
+ if step > 0:
768
+ left_to_right = 1
769
+ else:
770
+ left_to_right = 0
771
+ step = -step
772
+ _replaceSlice(self, c_node, slicelength, step, left_to_right, value)
773
+ return
774
+ else:
775
+ # otherwise: normal item assignment
776
+ element = value
777
+ _assertValidNode(element)
778
+ c_node = _findChild(self._c_node, x)
779
+ if c_node is NULL:
780
+ raise IndexError, "list index out of range"
781
+ c_source_doc = element._c_node.doc
782
+ c_next = element._c_node.next
783
+ _removeText(c_node.next)
784
+ tree.xmlReplaceNode(c_node, element._c_node)
785
+ _moveTail(c_next, element._c_node)
786
+ moveNodeToDocument(self._doc, c_source_doc, element._c_node)
787
+ if not attemptDeallocation(c_node):
788
+ moveNodeToDocument(self._doc, c_node.doc, c_node)
789
+
790
+ def __delitem__(self, x):
791
+ """__delitem__(self, x)
792
+
793
+ Deletes the given subelement or a slice.
794
+ """
795
+ cdef xmlNode* c_node = NULL
796
+ cdef xmlNode* c_next
797
+ cdef Py_ssize_t step = 0, slicelength = 0
798
+ _assertValidNode(self)
799
+ if isinstance(x, slice):
800
+ # slice deletion
801
+ if _isFullSlice(<slice>x):
802
+ c_node = self._c_node.children
803
+ if c_node is not NULL:
804
+ if not _isElement(c_node):
805
+ c_node = _nextElement(c_node)
806
+ while c_node is not NULL:
807
+ c_next = _nextElement(c_node)
808
+ _removeNode(self._doc, c_node)
809
+ c_node = c_next
810
+ else:
811
+ _findChildSlice(<slice>x, self._c_node, &c_node, &step, &slicelength)
812
+ _deleteSlice(self._doc, c_node, slicelength, step)
813
+ else:
814
+ # item deletion
815
+ c_node = _findChild(self._c_node, x)
816
+ if c_node is NULL:
817
+ raise IndexError, f"index out of range: {x}"
818
+ _removeNode(self._doc, c_node)
819
+
820
+ def __deepcopy__(self, memo):
821
+ "__deepcopy__(self, memo)"
822
+ return self.__copy__()
823
+
824
+ def __copy__(self):
825
+ "__copy__(self)"
826
+ cdef xmlDoc* c_doc
827
+ cdef xmlNode* c_node
828
+ cdef _Document new_doc
829
+ _assertValidNode(self)
830
+ c_doc = _copyDocRoot(self._doc._c_doc, self._c_node) # recursive
831
+ new_doc = _documentFactory(c_doc, self._doc._parser)
832
+ root = new_doc.getroot()
833
+ if root is not None:
834
+ return root
835
+ # Comment/PI
836
+ c_node = c_doc.children
837
+ while c_node is not NULL and c_node.type != self._c_node.type:
838
+ c_node = c_node.next
839
+ if c_node is NULL:
840
+ return None
841
+ return _elementFactory(new_doc, c_node)
842
+
843
+ def set(self, key, value):
844
+ """set(self, key, value)
845
+
846
+ Sets an element attribute.
847
+ In HTML documents (not XML or XHTML), the value None is allowed and creates
848
+ an attribute without value (just the attribute name).
849
+ """
850
+ _assertValidNode(self)
851
+ _setAttributeValue(self, key, value)
852
+
853
+ def append(self, _Element element not None):
854
+ """append(self, element)
855
+
856
+ Adds a subelement to the end of this element.
857
+ """
858
+ _assertValidNode(self)
859
+ _assertValidNode(element)
860
+ _appendChild(self, element)
861
+
862
+ def addnext(self, _Element element not None):
863
+ """addnext(self, element)
864
+
865
+ Adds the element as a following sibling directly after this
866
+ element.
867
+
868
+ This is normally used to set a processing instruction or comment after
869
+ the root node of a document. Note that tail text is automatically
870
+ discarded when adding at the root level.
871
+ """
872
+ _assertValidNode(self)
873
+ _assertValidNode(element)
874
+ if self._c_node.parent != NULL and not _isElement(self._c_node.parent):
875
+ if element._c_node.type not in (tree.XML_PI_NODE, tree.XML_COMMENT_NODE):
876
+ raise TypeError, "Only processing instructions and comments can be siblings of the root element"
877
+ element.tail = None
878
+ _appendSibling(self, element)
879
+
880
+ def addprevious(self, _Element element not None):
881
+ """addprevious(self, element)
882
+
883
+ Adds the element as a preceding sibling directly before this
884
+ element.
885
+
886
+ This is normally used to set a processing instruction or comment
887
+ before the root node of a document. Note that tail text is
888
+ automatically discarded when adding at the root level.
889
+ """
890
+ _assertValidNode(self)
891
+ _assertValidNode(element)
892
+ if self._c_node.parent != NULL and not _isElement(self._c_node.parent):
893
+ if element._c_node.type != tree.XML_PI_NODE:
894
+ if element._c_node.type != tree.XML_COMMENT_NODE:
895
+ raise TypeError, "Only processing instructions and comments can be siblings of the root element"
896
+ element.tail = None
897
+ _prependSibling(self, element)
898
+
899
+ def extend(self, elements):
900
+ """extend(self, elements)
901
+
902
+ Extends the current children by the elements in the iterable.
903
+ """
904
+ cdef _Element element
905
+ _assertValidNode(self)
906
+ for element in elements:
907
+ if element is None:
908
+ raise TypeError, "Node must not be None"
909
+ _assertValidNode(element)
910
+ _appendChild(self, element)
911
+
912
+ def clear(self, bint keep_tail=False):
913
+ """clear(self, keep_tail=False)
914
+
915
+ Resets an element. This function removes all subelements, clears
916
+ all attributes and sets the text and tail properties to None.
917
+
918
+ Pass ``keep_tail=True`` to leave the tail text untouched.
919
+ """
920
+ cdef xmlAttr* c_attr
921
+ cdef xmlAttr* c_attr_next
922
+ cdef xmlNode* c_node
923
+ cdef xmlNode* c_node_next
924
+ _assertValidNode(self)
925
+ c_node = self._c_node
926
+ # remove self.text and self.tail
927
+ _removeText(c_node.children)
928
+ if not keep_tail:
929
+ _removeText(c_node.next)
930
+ # remove all attributes
931
+ c_attr = c_node.properties
932
+ if c_attr:
933
+ c_node.properties = NULL
934
+ tree.xmlFreePropList(c_attr)
935
+ # remove all subelements
936
+ c_node = c_node.children
937
+ if c_node and not _isElement(c_node):
938
+ c_node = _nextElement(c_node)
939
+ while c_node is not NULL:
940
+ c_node_next = _nextElement(c_node)
941
+ _removeNode(self._doc, c_node)
942
+ c_node = c_node_next
943
+
944
+ def insert(self, index: int, _Element element not None):
945
+ """insert(self, index, element)
946
+
947
+ Inserts a subelement at the given position in this element
948
+ """
949
+ cdef xmlNode* c_node
950
+ cdef xmlNode* c_next
951
+ cdef xmlDoc* c_source_doc
952
+ _assertValidNode(self)
953
+ _assertValidNode(element)
954
+ c_node = _findChild(self._c_node, index)
955
+ if c_node is NULL:
956
+ _appendChild(self, element)
957
+ return
958
+ # prevent cycles
959
+ if _isAncestorOrSame(element._c_node, self._c_node):
960
+ raise ValueError("cannot append parent to itself")
961
+ c_source_doc = element._c_node.doc
962
+ c_next = element._c_node.next
963
+ tree.xmlAddPrevSibling(c_node, element._c_node)
964
+ _moveTail(c_next, element._c_node)
965
+ moveNodeToDocument(self._doc, c_source_doc, element._c_node)
966
+
967
+ def remove(self, _Element element not None):
968
+ """remove(self, element)
969
+
970
+ Removes a matching subelement. Unlike the find methods, this
971
+ method compares elements based on identity, not on tag value
972
+ or contents.
973
+ """
974
+ cdef xmlNode* c_node
975
+ cdef xmlNode* c_next
976
+ _assertValidNode(self)
977
+ _assertValidNode(element)
978
+ c_node = element._c_node
979
+ if c_node.parent is not self._c_node:
980
+ raise ValueError, "Element is not a child of this node."
981
+ c_next = element._c_node.next
982
+ tree.xmlUnlinkNode(c_node)
983
+ _moveTail(c_next, c_node)
984
+ # fix namespace declarations
985
+ moveNodeToDocument(self._doc, c_node.doc, c_node)
986
+
987
+ def replace(self, _Element old_element not None,
988
+ _Element new_element not None):
989
+ """replace(self, old_element, new_element)
990
+
991
+ Replaces a subelement with the element passed as second argument.
992
+ """
993
+ cdef xmlNode* c_old_node
994
+ cdef xmlNode* c_old_next
995
+ cdef xmlNode* c_new_node
996
+ cdef xmlNode* c_new_next
997
+ cdef xmlDoc* c_source_doc
998
+ _assertValidNode(self)
999
+ _assertValidNode(old_element)
1000
+ _assertValidNode(new_element)
1001
+ c_old_node = old_element._c_node
1002
+ if c_old_node.parent is not self._c_node:
1003
+ raise ValueError, "Element is not a child of this node."
1004
+ c_new_node = new_element._c_node
1005
+ # prevent cycles
1006
+ if _isAncestorOrSame(c_new_node, self._c_node):
1007
+ raise ValueError("cannot append parent to itself")
1008
+ # replace node
1009
+ c_old_next = c_old_node.next
1010
+ c_new_next = c_new_node.next
1011
+ c_source_doc = c_new_node.doc
1012
+ tree.xmlReplaceNode(c_old_node, c_new_node)
1013
+ _moveTail(c_new_next, c_new_node)
1014
+ _moveTail(c_old_next, c_old_node)
1015
+ moveNodeToDocument(self._doc, c_source_doc, c_new_node)
1016
+ # fix namespace declarations
1017
+ moveNodeToDocument(self._doc, c_old_node.doc, c_old_node)
1018
+
1019
+ # PROPERTIES
1020
+ property tag:
1021
+ """Element tag
1022
+ """
1023
+ def __get__(self):
1024
+ if self._tag is not None:
1025
+ return self._tag
1026
+ _assertValidNode(self)
1027
+ self._tag = _namespacedName(self._c_node)
1028
+ return self._tag
1029
+
1030
+ def __set__(self, value):
1031
+ cdef _BaseParser parser
1032
+ _assertValidNode(self)
1033
+ ns, name = _getNsTag(value)
1034
+ parser = self._doc._parser
1035
+ if parser is not None and parser._for_html:
1036
+ _htmlTagValidOrRaise(name)
1037
+ else:
1038
+ _tagValidOrRaise(name)
1039
+ self._tag = value
1040
+ tree.xmlNodeSetName(self._c_node, _xcstr(name))
1041
+ if ns is None:
1042
+ self._c_node.ns = NULL
1043
+ else:
1044
+ self._doc._setNodeNs(self._c_node, _xcstr(ns))
1045
+
1046
+ @property
1047
+ def attrib(self):
1048
+ """Element attribute dictionary. Where possible, use get(), set(),
1049
+ keys(), values() and items() to access element attributes.
1050
+ """
1051
+ return _Attrib.__new__(_Attrib, self)
1052
+
1053
+ property text:
1054
+ """Text before the first subelement. This is either a string or
1055
+ the value None, if there was no text.
1056
+ """
1057
+ def __get__(self):
1058
+ _assertValidNode(self)
1059
+ return _collectText(self._c_node.children)
1060
+
1061
+ def __set__(self, value):
1062
+ _assertValidNode(self)
1063
+ if isinstance(value, QName):
1064
+ value = _resolveQNameText(self, value).decode('utf8')
1065
+ _setNodeText(self._c_node, value)
1066
+
1067
+ # using 'del el.text' is the wrong thing to do
1068
+ #def __del__(self):
1069
+ # _setNodeText(self._c_node, None)
1070
+
1071
+ property tail:
1072
+ """Text after this element's end tag, but before the next sibling
1073
+ element's start tag. This is either a string or the value None, if
1074
+ there was no text.
1075
+ """
1076
+ def __get__(self):
1077
+ _assertValidNode(self)
1078
+ return _collectText(self._c_node.next)
1079
+
1080
+ def __set__(self, value):
1081
+ _assertValidNode(self)
1082
+ _setTailText(self._c_node, value)
1083
+
1084
+ # using 'del el.tail' is the wrong thing to do
1085
+ #def __del__(self):
1086
+ # _setTailText(self._c_node, None)
1087
+
1088
+ # not in ElementTree, read-only
1089
+ @property
1090
+ def prefix(self):
1091
+ """Namespace prefix or None.
1092
+ """
1093
+ if self._c_node.ns is not NULL:
1094
+ if self._c_node.ns.prefix is not NULL:
1095
+ return funicode(self._c_node.ns.prefix)
1096
+ return None
1097
+
1098
+ # not in ElementTree, read-only
1099
+ property sourceline:
1100
+ """Original line number as found by the parser or None if unknown.
1101
+ """
1102
+ def __get__(self):
1103
+ cdef long line
1104
+ _assertValidNode(self)
1105
+ line = tree.xmlGetLineNo(self._c_node)
1106
+ return line if line > 0 else None
1107
+
1108
+ def __set__(self, line):
1109
+ _assertValidNode(self)
1110
+ if line <= 0:
1111
+ self._c_node.line = 0
1112
+ else:
1113
+ self._c_node.line = line
1114
+
1115
+ # not in ElementTree, read-only
1116
+ @property
1117
+ def nsmap(self):
1118
+ """Namespace prefix->URI mapping known in the context of this
1119
+ Element. This includes all namespace declarations of the
1120
+ parents.
1121
+
1122
+ Note that changing the returned dict has no effect on the Element.
1123
+ """
1124
+ _assertValidNode(self)
1125
+ return _build_nsmap(self._c_node)
1126
+
1127
+ # not in ElementTree, read-only
1128
+ property base:
1129
+ """The base URI of the Element (xml:base or HTML base URL).
1130
+ None if the base URI is unknown.
1131
+
1132
+ Note that the value depends on the URL of the document that
1133
+ holds the Element if there is no xml:base attribute on the
1134
+ Element or its ancestors.
1135
+
1136
+ Setting this property will set an xml:base attribute on the
1137
+ Element, regardless of the document type (XML or HTML).
1138
+ """
1139
+ def __get__(self):
1140
+ _assertValidNode(self)
1141
+ c_base = tree.xmlNodeGetBase(self._doc._c_doc, self._c_node)
1142
+ if c_base is NULL:
1143
+ if self._doc._c_doc.URL is NULL:
1144
+ return None
1145
+ return _decodeFilename(self._doc._c_doc.URL)
1146
+ try:
1147
+ base = _decodeFilename(c_base)
1148
+ finally:
1149
+ tree.xmlFree(c_base)
1150
+ return base
1151
+
1152
+ def __set__(self, url):
1153
+ _assertValidNode(self)
1154
+ if url is None:
1155
+ c_base = <const_xmlChar*>NULL
1156
+ else:
1157
+ url = _encodeFilename(url)
1158
+ c_base = _xcstr(url)
1159
+ tree.xmlNodeSetBase(self._c_node, c_base)
1160
+
1161
+ # ACCESSORS
1162
+ def __repr__(self):
1163
+ "__repr__(self)"
1164
+ return "<Element %s at 0x%x>" % (self.tag, id(self))
1165
+
1166
+ def __getitem__(self, x):
1167
+ """Returns the subelement at the given position or the requested
1168
+ slice.
1169
+ """
1170
+ cdef xmlNode* c_node = NULL
1171
+ cdef Py_ssize_t step = 0, slicelength = 0
1172
+ cdef Py_ssize_t c, i
1173
+ cdef _node_to_node_function next_element
1174
+ cdef list result
1175
+ _assertValidNode(self)
1176
+ if isinstance(x, slice):
1177
+ # slicing
1178
+ if _isFullSlice(<slice>x):
1179
+ return _collectChildren(self)
1180
+ _findChildSlice(<slice>x, self._c_node, &c_node, &step, &slicelength)
1181
+ if c_node is NULL:
1182
+ return []
1183
+ if step > 0:
1184
+ next_element = _nextElement
1185
+ else:
1186
+ step = -step
1187
+ next_element = _previousElement
1188
+ result = []
1189
+ c = 0
1190
+ while c_node is not NULL and c < slicelength:
1191
+ result.append(_elementFactory(self._doc, c_node))
1192
+ c += 1
1193
+ for i in range(step):
1194
+ c_node = next_element(c_node)
1195
+ if c_node is NULL:
1196
+ break
1197
+ return result
1198
+ else:
1199
+ # indexing
1200
+ c_node = _findChild(self._c_node, x)
1201
+ if c_node is NULL:
1202
+ raise IndexError, "list index out of range"
1203
+ return _elementFactory(self._doc, c_node)
1204
+
1205
+ def __len__(self):
1206
+ """__len__(self)
1207
+
1208
+ Returns the number of subelements.
1209
+ """
1210
+ _assertValidNode(self)
1211
+ return _countElements(self._c_node.children)
1212
+
1213
+ def __bool__(self):
1214
+ """__bool__(self)"""
1215
+ import warnings
1216
+ warnings.warn(
1217
+ "The behavior of this method will change in future versions. "
1218
+ "Use specific 'len(elem)' or 'elem is not None' test instead.",
1219
+ FutureWarning
1220
+ )
1221
+ # emulate old behaviour
1222
+ _assertValidNode(self)
1223
+ return _hasChild(self._c_node)
1224
+
1225
+ def __contains__(self, element):
1226
+ "__contains__(self, element)"
1227
+ cdef xmlNode* c_node
1228
+ _assertValidNode(self)
1229
+ if not isinstance(element, _Element):
1230
+ return 0
1231
+ c_node = (<_Element>element)._c_node
1232
+ return c_node is not NULL and c_node.parent is self._c_node
1233
+
1234
+ def __iter__(self):
1235
+ "__iter__(self)"
1236
+ return ElementChildIterator(self)
1237
+
1238
+ def __reversed__(self):
1239
+ "__reversed__(self)"
1240
+ return ElementChildIterator(self, reversed=True)
1241
+
1242
+ def index(self, child: _Element, start: int = None, stop: int = None):
1243
+ """index(self, child, start=None, stop=None)
1244
+
1245
+ Find the position of the child within the parent.
1246
+
1247
+ This method is not part of the original ElementTree API.
1248
+ """
1249
+ cdef Py_ssize_t k, l
1250
+ cdef Py_ssize_t c_start, c_stop
1251
+ cdef xmlNode* c_child
1252
+ cdef xmlNode* c_start_node
1253
+ _assertValidNode(self)
1254
+ _assertValidNode(child)
1255
+ c_child = child._c_node
1256
+ if c_child.parent is not self._c_node:
1257
+ raise ValueError, "Element is not a child of this node."
1258
+
1259
+ # handle the unbounded search straight away (normal case)
1260
+ if stop is None and (start is None or start == 0):
1261
+ k = 0
1262
+ c_child = c_child.prev
1263
+ while c_child is not NULL:
1264
+ if _isElement(c_child):
1265
+ k += 1
1266
+ c_child = c_child.prev
1267
+ return k
1268
+
1269
+ # check indices
1270
+ if start is None:
1271
+ c_start = 0
1272
+ else:
1273
+ c_start = start
1274
+ if stop is None:
1275
+ c_stop = 0
1276
+ else:
1277
+ c_stop = stop
1278
+ if c_stop == 0 or \
1279
+ c_start >= c_stop and (c_stop > 0 or c_start < 0):
1280
+ raise ValueError, "list.index(x): x not in slice"
1281
+
1282
+ # for negative slice indices, check slice before searching index
1283
+ if c_start < 0 or c_stop < 0:
1284
+ # start from right, at most up to leftmost(c_start, c_stop)
1285
+ if c_start < c_stop:
1286
+ k = -c_start
1287
+ else:
1288
+ k = -c_stop
1289
+ c_start_node = self._c_node.last
1290
+ l = 1
1291
+ while c_start_node != c_child and l < k:
1292
+ if _isElement(c_start_node):
1293
+ l += 1
1294
+ c_start_node = c_start_node.prev
1295
+ if c_start_node == c_child:
1296
+ # found! before slice end?
1297
+ if c_stop < 0 and l <= -c_stop:
1298
+ raise ValueError, "list.index(x): x not in slice"
1299
+ elif c_start < 0:
1300
+ raise ValueError, "list.index(x): x not in slice"
1301
+
1302
+ # now determine the index backwards from child
1303
+ c_child = c_child.prev
1304
+ k = 0
1305
+ if c_stop > 0:
1306
+ # we can optimize: stop after c_stop elements if not found
1307
+ while c_child != NULL and k < c_stop:
1308
+ if _isElement(c_child):
1309
+ k += 1
1310
+ c_child = c_child.prev
1311
+ if k < c_stop:
1312
+ return k
1313
+ else:
1314
+ # traverse all
1315
+ while c_child != NULL:
1316
+ if _isElement(c_child):
1317
+ k = k + 1
1318
+ c_child = c_child.prev
1319
+ if c_start > 0:
1320
+ if k >= c_start:
1321
+ return k
1322
+ else:
1323
+ return k
1324
+ if c_start != 0 or c_stop != 0:
1325
+ raise ValueError, "list.index(x): x not in slice"
1326
+ else:
1327
+ raise ValueError, "list.index(x): x not in list"
1328
+
1329
+ def get(self, key, default=None):
1330
+ """get(self, key, default=None)
1331
+
1332
+ Gets an element attribute.
1333
+ """
1334
+ _assertValidNode(self)
1335
+ return _getAttributeValue(self, key, default)
1336
+
1337
+ def keys(self):
1338
+ """keys(self)
1339
+
1340
+ Gets a list of attribute names. The names are returned in an
1341
+ arbitrary order (just like for an ordinary Python dictionary).
1342
+ """
1343
+ _assertValidNode(self)
1344
+ return _collectAttributes(self._c_node, 1)
1345
+
1346
+ def values(self):
1347
+ """values(self)
1348
+
1349
+ Gets element attribute values as a sequence of strings. The
1350
+ attributes are returned in an arbitrary order.
1351
+ """
1352
+ _assertValidNode(self)
1353
+ return _collectAttributes(self._c_node, 2)
1354
+
1355
+ def items(self):
1356
+ """items(self)
1357
+
1358
+ Gets element attributes, as a sequence. The attributes are returned in
1359
+ an arbitrary order.
1360
+ """
1361
+ _assertValidNode(self)
1362
+ return _collectAttributes(self._c_node, 3)
1363
+
1364
+ def getchildren(self):
1365
+ """getchildren(self)
1366
+
1367
+ Returns all direct children. The elements are returned in document
1368
+ order.
1369
+
1370
+ :deprecated: Note that this method has been deprecated as of
1371
+ ElementTree 1.3 and lxml 2.0. New code should use
1372
+ ``list(element)`` or simply iterate over elements.
1373
+ """
1374
+ _assertValidNode(self)
1375
+ return _collectChildren(self)
1376
+
1377
+ def getparent(self):
1378
+ """getparent(self)
1379
+
1380
+ Returns the parent of this element or None for the root element.
1381
+ """
1382
+ cdef xmlNode* c_node
1383
+ #_assertValidNode(self) # not needed
1384
+ c_node = _parentElement(self._c_node)
1385
+ if c_node is NULL:
1386
+ return None
1387
+ return _elementFactory(self._doc, c_node)
1388
+
1389
+ def getnext(self):
1390
+ """getnext(self)
1391
+
1392
+ Returns the following sibling of this element or None.
1393
+ """
1394
+ cdef xmlNode* c_node
1395
+ #_assertValidNode(self) # not needed
1396
+ c_node = _nextElement(self._c_node)
1397
+ if c_node is NULL:
1398
+ return None
1399
+ return _elementFactory(self._doc, c_node)
1400
+
1401
+ def getprevious(self):
1402
+ """getprevious(self)
1403
+
1404
+ Returns the preceding sibling of this element or None.
1405
+ """
1406
+ cdef xmlNode* c_node
1407
+ #_assertValidNode(self) # not needed
1408
+ c_node = _previousElement(self._c_node)
1409
+ if c_node is NULL:
1410
+ return None
1411
+ return _elementFactory(self._doc, c_node)
1412
+
1413
+ def itersiblings(self, tag=None, *tags, preceding=False):
1414
+ """itersiblings(self, tag=None, *tags, preceding=False)
1415
+
1416
+ Iterate over the following or preceding siblings of this element.
1417
+
1418
+ The direction is determined by the 'preceding' keyword which
1419
+ defaults to False, i.e. forward iteration over the following
1420
+ siblings. When True, the iterator yields the preceding
1421
+ siblings in reverse document order, i.e. starting right before
1422
+ the current element and going backwards.
1423
+
1424
+ Can be restricted to find only elements with specific tags,
1425
+ see `iter`.
1426
+ """
1427
+ if preceding:
1428
+ if self._c_node and not self._c_node.prev:
1429
+ return ITER_EMPTY
1430
+ elif self._c_node and not self._c_node.next:
1431
+ return ITER_EMPTY
1432
+ if tag is not None:
1433
+ tags += (tag,)
1434
+ return SiblingsIterator(self, tags, preceding=preceding)
1435
+
1436
+ def iterancestors(self, tag=None, *tags):
1437
+ """iterancestors(self, tag=None, *tags)
1438
+
1439
+ Iterate over the ancestors of this element (from parent to parent).
1440
+
1441
+ Can be restricted to find only elements with specific tags,
1442
+ see `iter`.
1443
+ """
1444
+ if self._c_node and not self._c_node.parent:
1445
+ return ITER_EMPTY
1446
+ if tag is not None:
1447
+ tags += (tag,)
1448
+ return AncestorsIterator(self, tags)
1449
+
1450
+ def iterdescendants(self, tag=None, *tags):
1451
+ """iterdescendants(self, tag=None, *tags)
1452
+
1453
+ Iterate over the descendants of this element in document order.
1454
+
1455
+ As opposed to ``el.iter()``, this iterator does not yield the element
1456
+ itself. The returned elements can be restricted to find only elements
1457
+ with specific tags, see `iter`.
1458
+ """
1459
+ if self._c_node and not self._c_node.children:
1460
+ return ITER_EMPTY
1461
+ if tag is not None:
1462
+ tags += (tag,)
1463
+ return ElementDepthFirstIterator(self, tags, inclusive=False)
1464
+
1465
+ def iterchildren(self, tag=None, *tags, reversed=False):
1466
+ """iterchildren(self, tag=None, *tags, reversed=False)
1467
+
1468
+ Iterate over the children of this element.
1469
+
1470
+ As opposed to using normal iteration on this element, the returned
1471
+ elements can be reversed with the 'reversed' keyword and restricted
1472
+ to find only elements with specific tags, see `iter`.
1473
+ """
1474
+ if self._c_node and not self._c_node.children:
1475
+ return ITER_EMPTY
1476
+ if tag is not None:
1477
+ tags += (tag,)
1478
+ return ElementChildIterator(self, tags, reversed=reversed)
1479
+
1480
+ def getroottree(self):
1481
+ """getroottree(self)
1482
+
1483
+ Return an ElementTree for the root node of the document that
1484
+ contains this element.
1485
+
1486
+ This is the same as following element.getparent() up the tree until it
1487
+ returns None (for the root element) and then build an ElementTree for
1488
+ the last parent that was returned."""
1489
+ _assertValidDoc(self._doc)
1490
+ return _elementTreeFactory(self._doc, None)
1491
+
1492
+ def getiterator(self, tag=None, *tags):
1493
+ """getiterator(self, tag=None, *tags)
1494
+
1495
+ Returns a sequence or iterator of all elements in the subtree in
1496
+ document order (depth first pre-order), starting with this
1497
+ element.
1498
+
1499
+ Can be restricted to find only elements with specific tags,
1500
+ see `iter`.
1501
+
1502
+ :deprecated: Note that this method is deprecated as of
1503
+ ElementTree 1.3 and lxml 2.0. It returns an iterator in
1504
+ lxml, which diverges from the original ElementTree
1505
+ behaviour. If you want an efficient iterator, use the
1506
+ ``element.iter()`` method instead. You should only use this
1507
+ method in new code if you require backwards compatibility
1508
+ with older versions of lxml or ElementTree.
1509
+ """
1510
+ if tag is not None:
1511
+ tags += (tag,)
1512
+ return ElementDepthFirstIterator(self, tags)
1513
+
1514
+ def iter(self, tag=None, *tags):
1515
+ """iter(self, tag=None, *tags)
1516
+
1517
+ Iterate over all elements in the subtree in document order (depth
1518
+ first pre-order), starting with this element.
1519
+
1520
+ Can be restricted to find only elements with specific tags:
1521
+ pass ``"{ns}localname"`` as tag. Either or both of ``ns`` and
1522
+ ``localname`` can be ``*`` for a wildcard; ``ns`` can be empty
1523
+ for no namespace. ``"localname"`` is equivalent to ``"{}localname"``
1524
+ (i.e. no namespace) but ``"*"`` is ``"{*}*"`` (any or no namespace),
1525
+ not ``"{}*"``.
1526
+
1527
+ You can also pass the Element, Comment, ProcessingInstruction and
1528
+ Entity factory functions to look only for the specific element type.
1529
+
1530
+ Passing multiple tags (or a sequence of tags) instead of a single tag
1531
+ will let the iterator return all elements matching any of these tags,
1532
+ in document order.
1533
+ """
1534
+ if tag is not None:
1535
+ tags += (tag,)
1536
+ return ElementDepthFirstIterator(self, tags)
1537
+
1538
+ def itertext(self, tag=None, *tags, with_tail=True):
1539
+ """itertext(self, tag=None, *tags, with_tail=True)
1540
+
1541
+ Iterates over the text content of a subtree.
1542
+
1543
+ You can pass tag names to restrict text content to specific elements,
1544
+ see `iter`.
1545
+
1546
+ You can set the ``with_tail`` keyword argument to ``False`` to skip
1547
+ over tail text.
1548
+ """
1549
+ if tag is not None:
1550
+ tags += (tag,)
1551
+ return ElementTextIterator(self, tags, with_tail=with_tail)
1552
+
1553
+ def makeelement(self, _tag, attrib=None, nsmap=None, **_extra):
1554
+ """makeelement(self, _tag, attrib=None, nsmap=None, **_extra)
1555
+
1556
+ Creates a new element associated with the same document.
1557
+ """
1558
+ _assertValidDoc(self._doc)
1559
+ return _makeElement(_tag, NULL, self._doc, None, None, None,
1560
+ attrib, nsmap, _extra)
1561
+
1562
+ def find(self, path, namespaces=None):
1563
+ """find(self, path, namespaces=None)
1564
+
1565
+ Finds the first matching subelement, by tag name or path.
1566
+
1567
+ The optional ``namespaces`` argument accepts a
1568
+ prefix-to-namespace mapping that allows the usage of XPath
1569
+ prefixes in the path expression.
1570
+ """
1571
+ if isinstance(path, QName):
1572
+ path = (<QName>path).text
1573
+ return _elementpath.find(self, path, namespaces, with_prefixes=not _isHtmlDocument(self))
1574
+
1575
+ def findtext(self, path, default=None, namespaces=None):
1576
+ """findtext(self, path, default=None, namespaces=None)
1577
+
1578
+ Finds text for the first matching subelement, by tag name or path.
1579
+
1580
+ The optional ``namespaces`` argument accepts a
1581
+ prefix-to-namespace mapping that allows the usage of XPath
1582
+ prefixes in the path expression.
1583
+ """
1584
+ if isinstance(path, QName):
1585
+ path = (<QName>path).text
1586
+ return _elementpath.findtext(self, path, default, namespaces, with_prefixes=not _isHtmlDocument(self))
1587
+
1588
+ def findall(self, path, namespaces=None):
1589
+ """findall(self, path, namespaces=None)
1590
+
1591
+ Finds all matching subelements, by tag name or path.
1592
+
1593
+ The optional ``namespaces`` argument accepts a
1594
+ prefix-to-namespace mapping that allows the usage of XPath
1595
+ prefixes in the path expression.
1596
+ """
1597
+ if isinstance(path, QName):
1598
+ path = (<QName>path).text
1599
+ return _elementpath.findall(self, path, namespaces, with_prefixes=not _isHtmlDocument(self))
1600
+
1601
+ def iterfind(self, path, namespaces=None):
1602
+ """iterfind(self, path, namespaces=None)
1603
+
1604
+ Iterates over all matching subelements, by tag name or path.
1605
+
1606
+ The optional ``namespaces`` argument accepts a
1607
+ prefix-to-namespace mapping that allows the usage of XPath
1608
+ prefixes in the path expression.
1609
+ """
1610
+ if isinstance(path, QName):
1611
+ path = (<QName>path).text
1612
+ return _elementpath.iterfind(self, path, namespaces, with_prefixes=not _isHtmlDocument(self))
1613
+
1614
+ def xpath(self, _path, *, namespaces=None, extensions=None,
1615
+ smart_strings=True, **_variables):
1616
+ """xpath(self, _path, namespaces=None, extensions=None, smart_strings=True, **_variables)
1617
+
1618
+ Evaluate an xpath expression using the element as context node.
1619
+ """
1620
+ evaluator = XPathElementEvaluator(self, namespaces=namespaces,
1621
+ extensions=extensions,
1622
+ smart_strings=smart_strings)
1623
+ return evaluator(_path, **_variables)
1624
+
1625
+ def cssselect(self, expr, *, translator='xml'):
1626
+ """
1627
+ Run the CSS expression on this element and its children,
1628
+ returning a list of the results.
1629
+
1630
+ Equivalent to lxml.cssselect.CSSSelect(expr)(self) -- note
1631
+ that pre-compiling the expression can provide a substantial
1632
+ speedup.
1633
+ """
1634
+ # Do the import here to make the dependency optional.
1635
+ from lxml.cssselect import CSSSelector
1636
+ return CSSSelector(expr, translator=translator)(self)
1637
+
1638
+
1639
+ cdef extern from "includes/etree_defs.h":
1640
+ # macro call to 't->tp_new()' for fast instantiation
1641
+ cdef object NEW_ELEMENT "PY_NEW" (object t)
1642
+
1643
+
1644
+ @cython.linetrace(False)
1645
+ cdef _Element _elementFactory(_Document doc, xmlNode* c_node):
1646
+ cdef _Element result
1647
+ result = getProxy(c_node)
1648
+ if result is not None:
1649
+ return result
1650
+ if c_node is NULL:
1651
+ return None
1652
+
1653
+ element_class = LOOKUP_ELEMENT_CLASS(
1654
+ ELEMENT_CLASS_LOOKUP_STATE, doc, c_node)
1655
+ if hasProxy(c_node):
1656
+ # prevent re-entry race condition - we just called into Python
1657
+ return getProxy(c_node)
1658
+ result = NEW_ELEMENT(element_class)
1659
+ if hasProxy(c_node):
1660
+ # prevent re-entry race condition - we just called into Python
1661
+ result._c_node = NULL
1662
+ return getProxy(c_node)
1663
+
1664
+ _registerProxy(result, doc, c_node)
1665
+ if element_class is not _Element:
1666
+ result._init()
1667
+ return result
1668
+
1669
+
1670
+ @cython.internal
1671
+ cdef class __ContentOnlyElement(_Element):
1672
+ cdef int _raiseImmutable(self) except -1:
1673
+ raise TypeError, "this element does not have children or attributes"
1674
+
1675
+ def set(self, key, value):
1676
+ "set(self, key, value)"
1677
+ self._raiseImmutable()
1678
+
1679
+ def append(self, value):
1680
+ "append(self, value)"
1681
+ self._raiseImmutable()
1682
+
1683
+ def insert(self, index, value):
1684
+ "insert(self, index, value)"
1685
+ self._raiseImmutable()
1686
+
1687
+ def __setitem__(self, index, value):
1688
+ "__setitem__(self, index, value)"
1689
+ self._raiseImmutable()
1690
+
1691
+ @property
1692
+ def attrib(self):
1693
+ return IMMUTABLE_EMPTY_MAPPING
1694
+
1695
+ property text:
1696
+ def __get__(self):
1697
+ _assertValidNode(self)
1698
+ return funicodeOrEmpty(self._c_node.content)
1699
+
1700
+ def __set__(self, value):
1701
+ cdef tree.xmlDict* c_dict
1702
+ _assertValidNode(self)
1703
+ if value is None:
1704
+ c_text = <const_xmlChar*>NULL
1705
+ else:
1706
+ value = _utf8(value)
1707
+ c_text = _xcstr(value)
1708
+ tree.xmlNodeSetContent(self._c_node, c_text)
1709
+
1710
+ # ACCESSORS
1711
+ def __getitem__(self, x):
1712
+ "__getitem__(self, x)"
1713
+ if isinstance(x, slice):
1714
+ return []
1715
+ else:
1716
+ raise IndexError, "list index out of range"
1717
+
1718
+ def __len__(self):
1719
+ "__len__(self)"
1720
+ return 0
1721
+
1722
+ def get(self, key, default=None):
1723
+ "get(self, key, default=None)"
1724
+ return None
1725
+
1726
+ def keys(self):
1727
+ "keys(self)"
1728
+ return []
1729
+
1730
+ def items(self):
1731
+ "items(self)"
1732
+ return []
1733
+
1734
+ def values(self):
1735
+ "values(self)"
1736
+ return []
1737
+
1738
+ cdef class _Comment(__ContentOnlyElement):
1739
+ @property
1740
+ def tag(self):
1741
+ return Comment
1742
+
1743
+ def __repr__(self):
1744
+ return "<!--%s-->" % self.text
1745
+
1746
+ cdef class _ProcessingInstruction(__ContentOnlyElement):
1747
+ @property
1748
+ def tag(self):
1749
+ return ProcessingInstruction
1750
+
1751
+ property target:
1752
+ # not in ElementTree
1753
+ def __get__(self):
1754
+ _assertValidNode(self)
1755
+ return funicode(self._c_node.name)
1756
+
1757
+ def __set__(self, value):
1758
+ _assertValidNode(self)
1759
+ value = _utf8(value)
1760
+ c_text = _xcstr(value)
1761
+ tree.xmlNodeSetName(self._c_node, c_text)
1762
+
1763
+ def __repr__(self):
1764
+ text = self.text
1765
+ if text:
1766
+ return "<?%s %s?>" % (self.target, text)
1767
+ else:
1768
+ return "<?%s?>" % self.target
1769
+
1770
+ def get(self, key, default=None):
1771
+ """get(self, key, default=None)
1772
+
1773
+ Try to parse pseudo-attributes from the text content of the
1774
+ processing instruction, search for one with the given key as
1775
+ name and return its associated value.
1776
+
1777
+ Note that this is only a convenience method for the most
1778
+ common case that all text content is structured in
1779
+ attribute-like name-value pairs with properly quoted values.
1780
+ It is not guaranteed to work for all possible text content.
1781
+ """
1782
+ return self.attrib.get(key, default)
1783
+
1784
+ @property
1785
+ def attrib(self):
1786
+ """Returns a dict containing all pseudo-attributes that can be
1787
+ parsed from the text content of this processing instruction.
1788
+ Note that modifying the dict currently has no effect on the
1789
+ XML node, although this is not guaranteed to stay this way.
1790
+ """
1791
+ return { attr : (value1 or value2)
1792
+ for attr, value1, value2 in _FIND_PI_ATTRIBUTES(' ' + self.text) }
1793
+
1794
+ cdef object _FIND_PI_ATTRIBUTES = re.compile(r'\s+(\w+)\s*=\s*(?:\'([^\']*)\'|"([^"]*)")', re.U).findall
1795
+
1796
+ cdef class _Entity(__ContentOnlyElement):
1797
+ @property
1798
+ def tag(self):
1799
+ return Entity
1800
+
1801
+ property name:
1802
+ # not in ElementTree
1803
+ def __get__(self):
1804
+ _assertValidNode(self)
1805
+ return funicode(self._c_node.name)
1806
+
1807
+ def __set__(self, value):
1808
+ _assertValidNode(self)
1809
+ value_utf = _utf8(value)
1810
+ if b'&' in value_utf or b';' in value_utf:
1811
+ raise ValueError, f"Invalid entity name '{value}'"
1812
+ tree.xmlNodeSetName(self._c_node, _xcstr(value_utf))
1813
+
1814
+ @property
1815
+ def text(self):
1816
+ # FIXME: should this be None or '&[VALUE];' or the resolved
1817
+ # entity value ?
1818
+ _assertValidNode(self)
1819
+ return f'&{funicode(self._c_node.name)};'
1820
+
1821
+ def __repr__(self):
1822
+ return "&%s;" % self.name
1823
+
1824
+
1825
+ cdef class QName:
1826
+ """QName(text_or_uri_or_element, tag=None)
1827
+
1828
+ QName wrapper for qualified XML names.
1829
+
1830
+ Pass a tag name by itself or a namespace URI and a tag name to
1831
+ create a qualified name. Alternatively, pass an Element to
1832
+ extract its tag name. ``None`` as first argument is ignored in
1833
+ order to allow for generic 2-argument usage.
1834
+
1835
+ The ``text`` property holds the qualified name in
1836
+ ``{namespace}tagname`` notation. The ``namespace`` and
1837
+ ``localname`` properties hold the respective parts of the tag
1838
+ name.
1839
+
1840
+ You can pass QName objects wherever a tag name is expected. Also,
1841
+ setting Element text from a QName will resolve the namespace prefix
1842
+ on assignment and set a qualified text value. This is helpful in XML
1843
+ languages like SOAP or XML-Schema that use prefixed tag names in
1844
+ their text content.
1845
+ """
1846
+ cdef readonly unicode text
1847
+ cdef readonly unicode localname
1848
+ cdef readonly unicode namespace
1849
+ def __init__(self, text_or_uri_or_element, tag=None):
1850
+ if text_or_uri_or_element is None:
1851
+ # Allow None as no namespace.
1852
+ text_or_uri_or_element, tag = tag, None
1853
+ if not _isString(text_or_uri_or_element):
1854
+ if isinstance(text_or_uri_or_element, _Element):
1855
+ text_or_uri_or_element = (<_Element>text_or_uri_or_element).tag
1856
+ if not _isString(text_or_uri_or_element):
1857
+ raise ValueError, f"Invalid input tag of type {type(text_or_uri_or_element)!r}"
1858
+ elif isinstance(text_or_uri_or_element, QName):
1859
+ text_or_uri_or_element = (<QName>text_or_uri_or_element).text
1860
+ elif text_or_uri_or_element is not None:
1861
+ text_or_uri_or_element = unicode(text_or_uri_or_element)
1862
+ else:
1863
+ raise ValueError, f"Invalid input tag of type {type(text_or_uri_or_element)!r}"
1864
+
1865
+ ns_utf, tag_utf = _getNsTag(text_or_uri_or_element)
1866
+ if tag is not None:
1867
+ # either ('ns', 'tag') or ('{ns}oldtag', 'newtag')
1868
+ if ns_utf is None:
1869
+ ns_utf = tag_utf # case 1: namespace ended up as tag name
1870
+ tag_utf = _utf8(tag)
1871
+ _tagValidOrRaise(tag_utf)
1872
+ self.localname = (<bytes>tag_utf).decode('utf8')
1873
+ if ns_utf is None:
1874
+ self.namespace = None
1875
+ self.text = self.localname
1876
+ else:
1877
+ self.namespace = (<bytes>ns_utf).decode('utf8')
1878
+ self.text = "{%s}%s" % (self.namespace, self.localname)
1879
+ def __str__(self):
1880
+ return self.text
1881
+ def __hash__(self):
1882
+ return hash(self.text)
1883
+ def __richcmp__(self, other, int op):
1884
+ try:
1885
+ if type(other) is QName:
1886
+ other = (<QName>other).text
1887
+ elif not isinstance(other, unicode):
1888
+ other = unicode(other)
1889
+ except (ValueError, UnicodeDecodeError):
1890
+ return NotImplemented
1891
+ return python.PyObject_RichCompare(self.text, other, op)
1892
+
1893
+
1894
+ cdef public class _ElementTree [ type LxmlElementTreeType,
1895
+ object LxmlElementTree ]:
1896
+ cdef _Document _doc
1897
+ cdef _Element _context_node
1898
+
1899
+ # Note that _doc is only used to store the original document if we do not
1900
+ # have a _context_node. All methods should prefer self._context_node._doc
1901
+ # to honour tree restructuring. _doc can happily be None!
1902
+
1903
+ @cython.final
1904
+ cdef int _assertHasRoot(self) except -1:
1905
+ """We have to take care here: the document may not have a root node!
1906
+ This can happen if ElementTree() is called without any argument and
1907
+ the caller 'forgets' to call parse() afterwards, so this is a bug in
1908
+ the caller program.
1909
+ """
1910
+ assert self._context_node is not None, \
1911
+ "ElementTree not initialized, missing root"
1912
+ return 0
1913
+
1914
+ def parse(self, source, _BaseParser parser=None, *, base_url=None):
1915
+ """parse(self, source, parser=None, base_url=None)
1916
+
1917
+ Updates self with the content of source and returns its root.
1918
+ """
1919
+ cdef _Document doc = None
1920
+ try:
1921
+ doc = _parseDocument(source, parser, base_url)
1922
+ except _TargetParserResult as result_container:
1923
+ # raises a TypeError if we don't get an _Element
1924
+ self._context_node = result_container.result
1925
+ else:
1926
+ self._context_node = doc.getroot()
1927
+ self._doc = None if self._context_node is not None else doc
1928
+ return self._context_node
1929
+
1930
+ def _setroot(self, _Element root not None):
1931
+ """_setroot(self, root)
1932
+
1933
+ Relocate the ElementTree to a new root node.
1934
+ """
1935
+ _assertValidNode(root)
1936
+ if root._c_node.type != tree.XML_ELEMENT_NODE:
1937
+ raise TypeError, "Only elements can be the root of an ElementTree"
1938
+ self._context_node = root
1939
+ self._doc = None
1940
+
1941
+ def getroot(self):
1942
+ """getroot(self)
1943
+
1944
+ Gets the root element for this tree.
1945
+ """
1946
+ return self._context_node
1947
+
1948
+ def __copy__(self):
1949
+ return _elementTreeFactory(self._doc, self._context_node)
1950
+
1951
+ def __deepcopy__(self, memo):
1952
+ cdef _Element root
1953
+ cdef _Document doc
1954
+ cdef xmlDoc* c_doc
1955
+ if self._context_node is not None:
1956
+ root = self._context_node.__copy__()
1957
+ assert root is not None
1958
+ _assertValidNode(root)
1959
+ _copyNonElementSiblings(self._context_node._c_node, root._c_node)
1960
+ return _elementTreeFactory(None, root)
1961
+ elif self._doc is not None:
1962
+ _assertValidDoc(self._doc)
1963
+ c_doc = tree.xmlCopyDoc(self._doc._c_doc, 1)
1964
+ if c_doc is NULL:
1965
+ raise MemoryError()
1966
+ doc = _documentFactory(c_doc, self._doc._parser)
1967
+ return _elementTreeFactory(doc, None)
1968
+ else:
1969
+ # so what ...
1970
+ return self
1971
+
1972
+ # not in ElementTree
1973
+ @property
1974
+ def docinfo(self) -> DocInfo:
1975
+ """Information about the document provided by parser and DTD."""
1976
+ self._assertHasRoot()
1977
+ return DocInfo(self._context_node._doc)
1978
+
1979
+ # not in ElementTree, read-only
1980
+ @property
1981
+ def parser(self):
1982
+ """The parser that was used to parse the document in this ElementTree.
1983
+ """
1984
+ if self._context_node is not None and \
1985
+ self._context_node._doc is not None:
1986
+ return self._context_node._doc._parser
1987
+ if self._doc is not None:
1988
+ return self._doc._parser
1989
+ return None
1990
+
1991
+ def write(self, file, *, encoding=None, method="xml",
1992
+ bint pretty_print=False, xml_declaration=None, bint with_tail=True,
1993
+ standalone=None, doctype=None, compression=0,
1994
+ bint exclusive=False, inclusive_ns_prefixes=None,
1995
+ bint with_comments=True, bint strip_text=False,
1996
+ docstring=None):
1997
+ """write(self, file, encoding=None, method="xml",
1998
+ pretty_print=False, xml_declaration=None, with_tail=True,
1999
+ standalone=None, doctype=None, compression=0,
2000
+ exclusive=False, inclusive_ns_prefixes=None,
2001
+ with_comments=True, strip_text=False)
2002
+
2003
+ Write the tree to a filename, file or file-like object.
2004
+
2005
+ Defaults to ASCII encoding and writing a declaration as needed.
2006
+
2007
+ The keyword argument 'method' selects the output method:
2008
+ 'xml', 'html', 'text', 'c14n' or 'c14n2'. Default is 'xml'.
2009
+
2010
+ With ``method="c14n"`` (C14N version 1), the options ``exclusive``,
2011
+ ``with_comments`` and ``inclusive_ns_prefixes`` request exclusive
2012
+ C14N, include comments, and list the inclusive prefixes respectively.
2013
+
2014
+ With ``method="c14n2"`` (C14N version 2), the ``with_comments`` and
2015
+ ``strip_text`` options control the output of comments and text space
2016
+ according to C14N 2.0.
2017
+
2018
+ Passing a boolean value to the ``standalone`` option will
2019
+ output an XML declaration with the corresponding
2020
+ ``standalone`` flag.
2021
+
2022
+ The ``doctype`` option allows passing in a plain string that will
2023
+ be serialised before the XML tree. Note that passing in non
2024
+ well-formed content here will make the XML output non well-formed.
2025
+ Also, an existing doctype in the document tree will not be removed
2026
+ when serialising an ElementTree instance.
2027
+
2028
+ The ``compression`` option enables GZip compression level 1-9.
2029
+
2030
+ The ``inclusive_ns_prefixes`` should be a list of namespace strings
2031
+ (i.e. ['xs', 'xsi']) that will be promoted to the top-level element
2032
+ during exclusive C14N serialisation. This parameter is ignored if
2033
+ exclusive mode=False.
2034
+
2035
+ If exclusive=True and no list is provided, a namespace will only be
2036
+ rendered if it is used by the immediate parent or one of its attributes
2037
+ and its prefix and values have not already been rendered by an ancestor
2038
+ of the namespace node's parent element.
2039
+ """
2040
+ cdef bint write_declaration
2041
+ cdef int is_standalone
2042
+
2043
+ self._assertHasRoot()
2044
+ _assertValidNode(self._context_node)
2045
+ if compression is None or compression < 0:
2046
+ compression = 0
2047
+
2048
+ # C14N serialisation
2049
+ if method in ('c14n', 'c14n2'):
2050
+ if encoding is not None:
2051
+ raise ValueError("Cannot specify encoding with C14N")
2052
+ if xml_declaration:
2053
+ raise ValueError("Cannot enable XML declaration in C14N")
2054
+
2055
+ if method == 'c14n':
2056
+ _tofilelikeC14N(file, self._context_node, exclusive, with_comments,
2057
+ compression, inclusive_ns_prefixes)
2058
+ else: # c14n2
2059
+ with _open_utf8_file(file, compression=compression) as f:
2060
+ target = C14NWriterTarget(
2061
+ f.write, with_comments=with_comments, strip_text=strip_text)
2062
+ _tree_to_target(self, target)
2063
+ return
2064
+
2065
+ if not with_comments:
2066
+ raise ValueError("Can only discard comments in C14N serialisation")
2067
+ # suppress decl. in default case (purely for ElementTree compatibility)
2068
+ if xml_declaration is not None:
2069
+ write_declaration = xml_declaration
2070
+ if encoding is None:
2071
+ encoding = 'ASCII'
2072
+ else:
2073
+ encoding = encoding.upper()
2074
+ elif encoding is None:
2075
+ encoding = 'ASCII'
2076
+ write_declaration = 0
2077
+ else:
2078
+ encoding = encoding.upper()
2079
+ write_declaration = encoding not in (
2080
+ 'US-ASCII', 'ASCII', 'UTF8', 'UTF-8')
2081
+ if standalone is None:
2082
+ is_standalone = -1
2083
+ elif standalone:
2084
+ write_declaration = 1
2085
+ is_standalone = 1
2086
+ else:
2087
+ write_declaration = 1
2088
+ is_standalone = 0
2089
+
2090
+ if docstring is not None and doctype is None:
2091
+ import warnings
2092
+ warnings.warn(
2093
+ "The 'docstring' option is deprecated. Use 'doctype' instead.",
2094
+ DeprecationWarning)
2095
+ doctype = docstring
2096
+
2097
+ _tofilelike(file, self._context_node, encoding, doctype, method,
2098
+ write_declaration, 1, pretty_print, with_tail,
2099
+ is_standalone, compression)
2100
+
2101
+ def getpath(self, _Element element not None):
2102
+ """getpath(self, element)
2103
+
2104
+ Returns a structural, absolute XPath expression to find the element.
2105
+
2106
+ For namespaced elements, the expression uses prefixes from the
2107
+ document, which therefore need to be provided in order to make any
2108
+ use of the expression in XPath.
2109
+
2110
+ Also see the method getelementpath(self, element), which returns a
2111
+ self-contained ElementPath expression.
2112
+ """
2113
+ cdef _Document doc
2114
+ cdef _Element root
2115
+ cdef xmlDoc* c_doc
2116
+ _assertValidNode(element)
2117
+ if self._context_node is not None:
2118
+ root = self._context_node
2119
+ doc = root._doc
2120
+ elif self._doc is not None:
2121
+ doc = self._doc
2122
+ root = doc.getroot()
2123
+ else:
2124
+ raise ValueError, "Element is not in this tree."
2125
+ _assertValidDoc(doc)
2126
+ _assertValidNode(root)
2127
+ if element._doc is not doc:
2128
+ raise ValueError, "Element is not in this tree."
2129
+
2130
+ c_doc = _fakeRootDoc(doc._c_doc, root._c_node)
2131
+ c_path = tree.xmlGetNodePath(element._c_node)
2132
+ _destroyFakeDoc(doc._c_doc, c_doc)
2133
+ if c_path is NULL:
2134
+ raise MemoryError()
2135
+ path = funicode(c_path)
2136
+ tree.xmlFree(c_path)
2137
+ return path
2138
+
2139
+ def getelementpath(self, _Element element not None):
2140
+ """getelementpath(self, element)
2141
+
2142
+ Returns a structural, absolute ElementPath expression to find the
2143
+ element. This path can be used in the .find() method to look up
2144
+ the element, provided that the elements along the path and their
2145
+ list of immediate children were not modified in between.
2146
+
2147
+ ElementPath has the advantage over an XPath expression (as returned
2148
+ by the .getpath() method) that it does not require additional prefix
2149
+ declarations. It is always self-contained.
2150
+ """
2151
+ cdef _Element root
2152
+ cdef Py_ssize_t count
2153
+ _assertValidNode(element)
2154
+ if element._c_node.type != tree.XML_ELEMENT_NODE:
2155
+ raise ValueError, "input is not an Element"
2156
+ if self._context_node is not None:
2157
+ root = self._context_node
2158
+ elif self._doc is not None:
2159
+ root = self._doc.getroot()
2160
+ else:
2161
+ raise ValueError, "Element is not in this tree"
2162
+ _assertValidNode(root)
2163
+ if element._doc is not root._doc:
2164
+ raise ValueError, "Element is not in this tree"
2165
+
2166
+ path = []
2167
+ c_element = element._c_node
2168
+ while c_element is not root._c_node:
2169
+ c_name = c_element.name
2170
+ c_href = _getNs(c_element)
2171
+ tag = _namespacedNameFromNsName(c_href, c_name)
2172
+ if c_href is NULL:
2173
+ c_href = <const_xmlChar*>b'' # no namespace (NULL is wildcard)
2174
+ # use tag[N] if there are preceding siblings with the same tag
2175
+ count = 0
2176
+ c_node = c_element.prev
2177
+ while c_node is not NULL:
2178
+ if c_node.type == tree.XML_ELEMENT_NODE:
2179
+ if _tagMatches(c_node, c_href, c_name):
2180
+ count += 1
2181
+ c_node = c_node.prev
2182
+ if count:
2183
+ tag = f'{tag}[{count+1}]'
2184
+ else:
2185
+ # use tag[1] if there are following siblings with the same tag
2186
+ c_node = c_element.next
2187
+ while c_node is not NULL:
2188
+ if c_node.type == tree.XML_ELEMENT_NODE:
2189
+ if _tagMatches(c_node, c_href, c_name):
2190
+ tag += '[1]'
2191
+ break
2192
+ c_node = c_node.next
2193
+
2194
+ path.append(tag)
2195
+ c_element = c_element.parent
2196
+ if c_element is NULL or c_element.type != tree.XML_ELEMENT_NODE:
2197
+ raise ValueError, "Element is not in this tree."
2198
+ if not path:
2199
+ return '.'
2200
+ path.reverse()
2201
+ return '/'.join(path)
2202
+
2203
+ def getiterator(self, tag=None, *tags):
2204
+ """getiterator(self, *tags, tag=None)
2205
+
2206
+ Returns a sequence or iterator of all elements in document order
2207
+ (depth first pre-order), starting with the root element.
2208
+
2209
+ Can be restricted to find only elements with specific tags,
2210
+ see `_Element.iter`.
2211
+
2212
+ :deprecated: Note that this method is deprecated as of
2213
+ ElementTree 1.3 and lxml 2.0. It returns an iterator in
2214
+ lxml, which diverges from the original ElementTree
2215
+ behaviour. If you want an efficient iterator, use the
2216
+ ``tree.iter()`` method instead. You should only use this
2217
+ method in new code if you require backwards compatibility
2218
+ with older versions of lxml or ElementTree.
2219
+ """
2220
+ root = self.getroot()
2221
+ if root is None:
2222
+ return ITER_EMPTY
2223
+ if tag is not None:
2224
+ tags += (tag,)
2225
+ return root.getiterator(*tags)
2226
+
2227
+ def iter(self, tag=None, *tags):
2228
+ """iter(self, tag=None, *tags)
2229
+
2230
+ Creates an iterator for the root element. The iterator loops over
2231
+ all elements in this tree, in document order. Note that siblings
2232
+ of the root element (comments or processing instructions) are not
2233
+ returned by the iterator.
2234
+
2235
+ Can be restricted to find only elements with specific tags,
2236
+ see `_Element.iter`.
2237
+ """
2238
+ root = self.getroot()
2239
+ if root is None:
2240
+ return ITER_EMPTY
2241
+ if tag is not None:
2242
+ tags += (tag,)
2243
+ return root.iter(*tags)
2244
+
2245
+ def find(self, path, namespaces=None):
2246
+ """find(self, path, namespaces=None)
2247
+
2248
+ Finds the first toplevel element with given tag. Same as
2249
+ ``tree.getroot().find(path)``.
2250
+
2251
+ The optional ``namespaces`` argument accepts a
2252
+ prefix-to-namespace mapping that allows the usage of XPath
2253
+ prefixes in the path expression.
2254
+ """
2255
+ self._assertHasRoot()
2256
+ root = self.getroot()
2257
+ if _isString(path):
2258
+ if path[:1] == "/":
2259
+ path = "." + path
2260
+ from warnings import warn
2261
+ warn(
2262
+ "This search incorrectly ignores the root element, and will be "
2263
+ "fixed in a future version. If you rely on the current "
2264
+ f"behaviour, change it to {path!r}",
2265
+ FutureWarning, stacklevel=1
2266
+ )
2267
+ return root.find(path, namespaces)
2268
+
2269
+ def findtext(self, path, default=None, namespaces=None):
2270
+ """findtext(self, path, default=None, namespaces=None)
2271
+
2272
+ Finds the text for the first element matching the ElementPath
2273
+ expression. Same as getroot().findtext(path)
2274
+
2275
+ The optional ``namespaces`` argument accepts a
2276
+ prefix-to-namespace mapping that allows the usage of XPath
2277
+ prefixes in the path expression.
2278
+ """
2279
+ self._assertHasRoot()
2280
+ root = self.getroot()
2281
+ if _isString(path):
2282
+ if path[:1] == "/":
2283
+ path = "." + path
2284
+ from warnings import warn
2285
+ warn(
2286
+ "This search incorrectly ignores the root element, and will be "
2287
+ "fixed in a future version. If you rely on the current "
2288
+ f"behaviour, change it to {path!r}",
2289
+ FutureWarning, stacklevel=1
2290
+ )
2291
+ return root.findtext(path, default, namespaces)
2292
+
2293
+ def findall(self, path, namespaces=None):
2294
+ """findall(self, path, namespaces=None)
2295
+
2296
+ Finds all elements matching the ElementPath expression. Same as
2297
+ getroot().findall(path).
2298
+
2299
+ The optional ``namespaces`` argument accepts a
2300
+ prefix-to-namespace mapping that allows the usage of XPath
2301
+ prefixes in the path expression.
2302
+ """
2303
+ self._assertHasRoot()
2304
+ root = self.getroot()
2305
+ if _isString(path):
2306
+ if path[:1] == "/":
2307
+ path = "." + path
2308
+ from warnings import warn
2309
+ warn(
2310
+ "This search incorrectly ignores the root element, and will be "
2311
+ "fixed in a future version. If you rely on the current "
2312
+ f"behaviour, change it to {path!r}",
2313
+ FutureWarning, stacklevel=1
2314
+ )
2315
+ return root.findall(path, namespaces)
2316
+
2317
+ def iterfind(self, path, namespaces=None):
2318
+ """iterfind(self, path, namespaces=None)
2319
+
2320
+ Iterates over all elements matching the ElementPath expression.
2321
+ Same as getroot().iterfind(path).
2322
+
2323
+ The optional ``namespaces`` argument accepts a
2324
+ prefix-to-namespace mapping that allows the usage of XPath
2325
+ prefixes in the path expression.
2326
+ """
2327
+ self._assertHasRoot()
2328
+ root = self.getroot()
2329
+ if _isString(path):
2330
+ if path[:1] == "/":
2331
+ path = "." + path
2332
+ from warnings import warn
2333
+ warn(
2334
+ "This search incorrectly ignores the root element, and will be "
2335
+ "fixed in a future version. If you rely on the current "
2336
+ f"behaviour, change it to {path!r}",
2337
+ FutureWarning, stacklevel=1
2338
+ )
2339
+ return root.iterfind(path, namespaces)
2340
+
2341
+ def xpath(self, _path, *, namespaces=None, extensions=None,
2342
+ smart_strings=True, **_variables):
2343
+ """xpath(self, _path, namespaces=None, extensions=None, smart_strings=True, **_variables)
2344
+
2345
+ XPath evaluate in context of document.
2346
+
2347
+ ``namespaces`` is an optional dictionary with prefix to namespace URI
2348
+ mappings, used by XPath. ``extensions`` defines additional extension
2349
+ functions.
2350
+
2351
+ Returns a list (nodeset), or bool, float or string.
2352
+
2353
+ In case of a list result, return Element for element nodes,
2354
+ string for text and attribute values.
2355
+
2356
+ Note: if you are going to apply multiple XPath expressions
2357
+ against the same document, it is more efficient to use
2358
+ XPathEvaluator directly.
2359
+ """
2360
+ self._assertHasRoot()
2361
+ evaluator = XPathDocumentEvaluator(self, namespaces=namespaces,
2362
+ extensions=extensions,
2363
+ smart_strings=smart_strings)
2364
+ return evaluator(_path, **_variables)
2365
+
2366
+ def xslt(self, _xslt, extensions=None, access_control=None, **_kw):
2367
+ """xslt(self, _xslt, extensions=None, access_control=None, **_kw)
2368
+
2369
+ Transform this document using other document.
2370
+
2371
+ xslt is a tree that should be XSLT
2372
+ keyword parameters are XSLT transformation parameters.
2373
+
2374
+ Returns the transformed tree.
2375
+
2376
+ Note: if you are going to apply the same XSLT stylesheet against
2377
+ multiple documents, it is more efficient to use the XSLT
2378
+ class directly.
2379
+ """
2380
+ self._assertHasRoot()
2381
+ style = XSLT(_xslt, extensions=extensions,
2382
+ access_control=access_control)
2383
+ return style(self, **_kw)
2384
+
2385
+ def relaxng(self, relaxng):
2386
+ """relaxng(self, relaxng)
2387
+
2388
+ Validate this document using other document.
2389
+
2390
+ The relaxng argument is a tree that should contain a Relax NG schema.
2391
+
2392
+ Returns True or False, depending on whether validation
2393
+ succeeded.
2394
+
2395
+ Note: if you are going to apply the same Relax NG schema against
2396
+ multiple documents, it is more efficient to use the RelaxNG
2397
+ class directly.
2398
+ """
2399
+ self._assertHasRoot()
2400
+ schema = RelaxNG(relaxng)
2401
+ return schema.validate(self)
2402
+
2403
+ def xmlschema(self, xmlschema):
2404
+ """xmlschema(self, xmlschema)
2405
+
2406
+ Validate this document using other document.
2407
+
2408
+ The xmlschema argument is a tree that should contain an XML Schema.
2409
+
2410
+ Returns True or False, depending on whether validation
2411
+ succeeded.
2412
+
2413
+ Note: If you are going to apply the same XML Schema against
2414
+ multiple documents, it is more efficient to use the XMLSchema
2415
+ class directly.
2416
+ """
2417
+ self._assertHasRoot()
2418
+ schema = XMLSchema(xmlschema)
2419
+ return schema.validate(self)
2420
+
2421
+ def xinclude(self):
2422
+ """xinclude(self)
2423
+
2424
+ Process the XInclude nodes in this document and include the
2425
+ referenced XML fragments.
2426
+
2427
+ There is support for loading files through the file system, HTTP and
2428
+ FTP.
2429
+
2430
+ Note that XInclude does not support custom resolvers in Python space
2431
+ due to restrictions of libxml2 <= 2.6.29.
2432
+ """
2433
+ self._assertHasRoot()
2434
+ XInclude()(self._context_node)
2435
+
2436
+ def write_c14n(self, file, *, bint exclusive=False, bint with_comments=True,
2437
+ compression=0, inclusive_ns_prefixes=None):
2438
+ """write_c14n(self, file, exclusive=False, with_comments=True,
2439
+ compression=0, inclusive_ns_prefixes=None)
2440
+
2441
+ C14N write of document. Always writes UTF-8.
2442
+
2443
+ The ``compression`` option enables GZip compression level 1-9.
2444
+
2445
+ The ``inclusive_ns_prefixes`` should be a list of namespace strings
2446
+ (i.e. ['xs', 'xsi']) that will be promoted to the top-level element
2447
+ during exclusive C14N serialisation. This parameter is ignored if
2448
+ exclusive mode=False.
2449
+
2450
+ If exclusive=True and no list is provided, a namespace will only be
2451
+ rendered if it is used by the immediate parent or one of its attributes
2452
+ and its prefix and values have not already been rendered by an ancestor
2453
+ of the namespace node's parent element.
2454
+
2455
+ NOTE: This method is deprecated as of lxml 4.4 and will be removed in a
2456
+ future release. Use ``.write(f, method="c14n")`` instead.
2457
+ """
2458
+ self._assertHasRoot()
2459
+ _assertValidNode(self._context_node)
2460
+ if compression is None or compression < 0:
2461
+ compression = 0
2462
+
2463
+ _tofilelikeC14N(file, self._context_node, exclusive, with_comments,
2464
+ compression, inclusive_ns_prefixes)
2465
+
2466
+ cdef _ElementTree _elementTreeFactory(_Document doc, _Element context_node):
2467
+ return _newElementTree(doc, context_node, _ElementTree)
2468
+
2469
+ cdef _ElementTree _newElementTree(_Document doc, _Element context_node,
2470
+ object baseclass):
2471
+ cdef _ElementTree result
2472
+ result = baseclass()
2473
+ if context_node is None and doc is not None:
2474
+ context_node = doc.getroot()
2475
+ if context_node is None:
2476
+ _assertValidDoc(doc)
2477
+ result._doc = doc
2478
+ else:
2479
+ _assertValidNode(context_node)
2480
+ result._context_node = context_node
2481
+ return result
2482
+
2483
+
2484
+ @cython.final
2485
+ @cython.freelist(16)
2486
+ cdef class _Attrib:
2487
+ """A dict-like proxy for the ``Element.attrib`` property.
2488
+ """
2489
+ cdef _Element _element
2490
+ def __cinit__(self, _Element element not None):
2491
+ _assertValidNode(element)
2492
+ self._element = element
2493
+
2494
+ # MANIPULATORS
2495
+ def __setitem__(self, key, value):
2496
+ _assertValidNode(self._element)
2497
+ _setAttributeValue(self._element, key, value)
2498
+
2499
+ def __delitem__(self, key):
2500
+ _assertValidNode(self._element)
2501
+ _delAttribute(self._element, key)
2502
+
2503
+ def update(self, sequence_or_dict):
2504
+ _assertValidNode(self._element)
2505
+ if isinstance(sequence_or_dict, (dict, _Attrib)):
2506
+ sequence_or_dict = sequence_or_dict.items()
2507
+ for key, value in sequence_or_dict:
2508
+ _setAttributeValue(self._element, key, value)
2509
+
2510
+ def pop(self, key, *default):
2511
+ if len(default) > 1:
2512
+ raise TypeError, f"pop expected at most 2 arguments, got {len(default)+1}"
2513
+ _assertValidNode(self._element)
2514
+ result = _getAttributeValue(self._element, key, None)
2515
+ if result is None:
2516
+ if not default:
2517
+ raise KeyError, key
2518
+ result = default[0]
2519
+ else:
2520
+ _delAttribute(self._element, key)
2521
+ return result
2522
+
2523
+ def clear(self):
2524
+ _assertValidNode(self._element)
2525
+ c_attrs = self._element._c_node.properties
2526
+ if c_attrs:
2527
+ self._element._c_node.properties = NULL
2528
+ tree.xmlFreePropList(c_attrs)
2529
+
2530
+ # ACCESSORS
2531
+ def __repr__(self):
2532
+ _assertValidNode(self._element)
2533
+ return repr(dict( _collectAttributes(self._element._c_node, 3) ))
2534
+
2535
+ def __copy__(self):
2536
+ _assertValidNode(self._element)
2537
+ return dict(_collectAttributes(self._element._c_node, 3))
2538
+
2539
+ def __deepcopy__(self, memo):
2540
+ _assertValidNode(self._element)
2541
+ return dict(_collectAttributes(self._element._c_node, 3))
2542
+
2543
+ def __getitem__(self, key):
2544
+ _assertValidNode(self._element)
2545
+ result = _getAttributeValue(self._element, key, None)
2546
+ if result is None:
2547
+ raise KeyError, key
2548
+ return result
2549
+
2550
+ def __bool__(self):
2551
+ _assertValidNode(self._element)
2552
+ cdef xmlAttr* c_attr = self._element._c_node.properties
2553
+ while c_attr is not NULL:
2554
+ if c_attr.type == tree.XML_ATTRIBUTE_NODE:
2555
+ return 1
2556
+ c_attr = c_attr.next
2557
+ return 0
2558
+
2559
+ def __len__(self):
2560
+ _assertValidNode(self._element)
2561
+ cdef xmlAttr* c_attr = self._element._c_node.properties
2562
+ cdef Py_ssize_t c = 0
2563
+ while c_attr is not NULL:
2564
+ if c_attr.type == tree.XML_ATTRIBUTE_NODE:
2565
+ c += 1
2566
+ c_attr = c_attr.next
2567
+ return c
2568
+
2569
+ def get(self, key, default=None):
2570
+ _assertValidNode(self._element)
2571
+ return _getAttributeValue(self._element, key, default)
2572
+
2573
+ def keys(self):
2574
+ _assertValidNode(self._element)
2575
+ return _collectAttributes(self._element._c_node, 1)
2576
+
2577
+ def __iter__(self):
2578
+ _assertValidNode(self._element)
2579
+ return iter(_collectAttributes(self._element._c_node, 1))
2580
+
2581
+ def iterkeys(self):
2582
+ _assertValidNode(self._element)
2583
+ return iter(_collectAttributes(self._element._c_node, 1))
2584
+
2585
+ def values(self):
2586
+ _assertValidNode(self._element)
2587
+ return _collectAttributes(self._element._c_node, 2)
2588
+
2589
+ def itervalues(self):
2590
+ _assertValidNode(self._element)
2591
+ return iter(_collectAttributes(self._element._c_node, 2))
2592
+
2593
+ def items(self):
2594
+ _assertValidNode(self._element)
2595
+ return _collectAttributes(self._element._c_node, 3)
2596
+
2597
+ def iteritems(self):
2598
+ _assertValidNode(self._element)
2599
+ return iter(_collectAttributes(self._element._c_node, 3))
2600
+
2601
+ def has_key(self, key):
2602
+ _assertValidNode(self._element)
2603
+ return key in self
2604
+
2605
+ def __contains__(self, key):
2606
+ _assertValidNode(self._element)
2607
+ cdef xmlNode* c_node
2608
+ ns, tag = _getNsTag(key)
2609
+ c_node = self._element._c_node
2610
+ c_href = <const_xmlChar*>NULL if ns is None else _xcstr(ns)
2611
+ return 1 if tree.xmlHasNsProp(c_node, _xcstr(tag), c_href) else 0
2612
+
2613
+ def __richcmp__(self, other, int op):
2614
+ try:
2615
+ one = dict(self.items())
2616
+ if not isinstance(other, dict):
2617
+ other = dict(other)
2618
+ except (TypeError, ValueError):
2619
+ return NotImplemented
2620
+ return python.PyObject_RichCompare(one, other, op)
2621
+
2622
+ MutableMapping.register(_Attrib)
2623
+
2624
+
2625
+ @cython.final
2626
+ @cython.internal
2627
+ cdef class _AttribIterator:
2628
+ """Attribute iterator - for internal use only!
2629
+ """
2630
+ # XML attributes must not be removed while running!
2631
+ cdef _Element _node
2632
+ cdef xmlAttr* _c_attr
2633
+ cdef int _keysvalues # 1 - keys, 2 - values, 3 - items (key, value)
2634
+ def __iter__(self):
2635
+ return self
2636
+
2637
+ def __next__(self):
2638
+ cdef xmlAttr* c_attr
2639
+ if self._node is None:
2640
+ raise StopIteration
2641
+ c_attr = self._c_attr
2642
+ while c_attr is not NULL and c_attr.type != tree.XML_ATTRIBUTE_NODE:
2643
+ c_attr = c_attr.next
2644
+ if c_attr is NULL:
2645
+ self._node = None
2646
+ raise StopIteration
2647
+
2648
+ self._c_attr = c_attr.next
2649
+ if self._keysvalues == 1:
2650
+ return _namespacedName(<xmlNode*>c_attr)
2651
+ elif self._keysvalues == 2:
2652
+ return _attributeValue(self._node._c_node, c_attr)
2653
+ else:
2654
+ return (_namespacedName(<xmlNode*>c_attr),
2655
+ _attributeValue(self._node._c_node, c_attr))
2656
+
2657
+ cdef object _attributeIteratorFactory(_Element element, int keysvalues):
2658
+ cdef _AttribIterator attribs
2659
+ if element._c_node.properties is NULL:
2660
+ return ITER_EMPTY
2661
+ attribs = _AttribIterator()
2662
+ attribs._node = element
2663
+ attribs._c_attr = element._c_node.properties
2664
+ attribs._keysvalues = keysvalues
2665
+ return attribs
2666
+
2667
+
2668
+ cdef public class _ElementTagMatcher [ object LxmlElementTagMatcher,
2669
+ type LxmlElementTagMatcherType ]:
2670
+ """
2671
+ Dead but public. :)
2672
+ """
2673
+ cdef object _pystrings
2674
+ cdef int _node_type
2675
+ cdef char* _href
2676
+ cdef char* _name
2677
+ cdef _initTagMatch(self, tag):
2678
+ self._href = NULL
2679
+ self._name = NULL
2680
+ if tag is None:
2681
+ self._node_type = 0
2682
+ elif tag is Comment:
2683
+ self._node_type = tree.XML_COMMENT_NODE
2684
+ elif tag is ProcessingInstruction:
2685
+ self._node_type = tree.XML_PI_NODE
2686
+ elif tag is Entity:
2687
+ self._node_type = tree.XML_ENTITY_REF_NODE
2688
+ elif tag is Element:
2689
+ self._node_type = tree.XML_ELEMENT_NODE
2690
+ else:
2691
+ self._node_type = tree.XML_ELEMENT_NODE
2692
+ self._pystrings = _getNsTag(tag)
2693
+ if self._pystrings[0] is not None:
2694
+ self._href = _cstr(self._pystrings[0])
2695
+ self._name = _cstr(self._pystrings[1])
2696
+ if self._name[0] == c'*' and self._name[1] == c'\0':
2697
+ self._name = NULL
2698
+
2699
+ cdef public class _ElementIterator(_ElementTagMatcher) [
2700
+ object LxmlElementIterator, type LxmlElementIteratorType ]:
2701
+ """
2702
+ Dead but public. :)
2703
+ """
2704
+ # we keep Python references here to control GC
2705
+ cdef _Element _node
2706
+ cdef _node_to_node_function _next_element
2707
+ def __iter__(self):
2708
+ return self
2709
+
2710
+ cdef void _storeNext(self, _Element node):
2711
+ cdef xmlNode* c_node
2712
+ c_node = self._next_element(node._c_node)
2713
+ while c_node is not NULL and \
2714
+ self._node_type != 0 and \
2715
+ (<tree.xmlElementType>self._node_type != c_node.type or
2716
+ not _tagMatches(c_node, <const_xmlChar*>self._href, <const_xmlChar*>self._name)):
2717
+ c_node = self._next_element(c_node)
2718
+ if c_node is NULL:
2719
+ self._node = None
2720
+ else:
2721
+ # Python ref:
2722
+ self._node = _elementFactory(node._doc, c_node)
2723
+
2724
+ def __next__(self):
2725
+ cdef xmlNode* c_node
2726
+ cdef _Element current_node
2727
+ if self._node is None:
2728
+ raise StopIteration
2729
+ # Python ref:
2730
+ current_node = self._node
2731
+ self._storeNext(current_node)
2732
+ return current_node
2733
+
2734
+ @cython.final
2735
+ @cython.internal
2736
+ cdef class _MultiTagMatcher:
2737
+ """
2738
+ Match an xmlNode against a list of tags.
2739
+ """
2740
+ cdef list _py_tags
2741
+ cdef qname* _cached_tags
2742
+ cdef size_t _tag_count
2743
+ cdef size_t _cached_size
2744
+ cdef _Document _cached_doc
2745
+ cdef int _node_types
2746
+
2747
+ def __cinit__(self, tags):
2748
+ self._py_tags = []
2749
+ self.initTagMatch(tags)
2750
+
2751
+ def __dealloc__(self):
2752
+ self._clear()
2753
+
2754
+ cdef bint rejectsAll(self) noexcept:
2755
+ return not self._tag_count and not self._node_types
2756
+
2757
+ cdef bint rejectsAllAttributes(self) noexcept:
2758
+ return not self._tag_count
2759
+
2760
+ cdef bint matchesType(self, int node_type) noexcept:
2761
+ if node_type == tree.XML_ELEMENT_NODE and self._tag_count:
2762
+ return True
2763
+ return self._node_types & (1 << node_type)
2764
+
2765
+ cdef void _clear(self) noexcept:
2766
+ cdef size_t i, count
2767
+ count = self._tag_count
2768
+ self._tag_count = 0
2769
+ if self._cached_tags:
2770
+ for i in range(count):
2771
+ cpython.ref.Py_XDECREF(self._cached_tags[i].href)
2772
+ python.lxml_free(self._cached_tags)
2773
+ self._cached_tags = NULL
2774
+
2775
+ cdef initTagMatch(self, tags):
2776
+ self._cached_doc = None
2777
+ del self._py_tags[:]
2778
+ self._clear()
2779
+ if tags is None or tags == ():
2780
+ # no selection in tags argument => match anything
2781
+ self._node_types = (
2782
+ 1 << tree.XML_COMMENT_NODE |
2783
+ 1 << tree.XML_PI_NODE |
2784
+ 1 << tree.XML_ENTITY_REF_NODE |
2785
+ 1 << tree.XML_ELEMENT_NODE)
2786
+ else:
2787
+ self._node_types = 0
2788
+ self._storeTags(tags, set())
2789
+
2790
+ cdef _storeTags(self, tag, set seen):
2791
+ if tag is Comment:
2792
+ self._node_types |= 1 << tree.XML_COMMENT_NODE
2793
+ elif tag is ProcessingInstruction:
2794
+ self._node_types |= 1 << tree.XML_PI_NODE
2795
+ elif tag is Entity:
2796
+ self._node_types |= 1 << tree.XML_ENTITY_REF_NODE
2797
+ elif tag is Element:
2798
+ self._node_types |= 1 << tree.XML_ELEMENT_NODE
2799
+ elif python._isString(tag):
2800
+ if tag in seen:
2801
+ return
2802
+ seen.add(tag)
2803
+ if tag in ('*', '{*}*'):
2804
+ self._node_types |= 1 << tree.XML_ELEMENT_NODE
2805
+ else:
2806
+ href, name = _getNsTag(tag)
2807
+ if name == b'*':
2808
+ name = None
2809
+ if href is None:
2810
+ href = b'' # no namespace
2811
+ elif href == b'*':
2812
+ href = None # wildcard: any namespace, including none
2813
+ self._py_tags.append((href, name))
2814
+ elif isinstance(tag, QName):
2815
+ self._storeTags(tag.text, seen)
2816
+ else:
2817
+ # support a sequence of tags
2818
+ for item in tag:
2819
+ self._storeTags(item, seen)
2820
+
2821
+ cdef inline int cacheTags(self, _Document doc, bint force_into_dict=False) except -1:
2822
+ """
2823
+ Look up the tag names in the doc dict to enable string pointer comparisons.
2824
+ """
2825
+ cdef size_t dict_size = tree.xmlDictSize(doc._c_doc.dict)
2826
+ if doc is self._cached_doc and dict_size == self._cached_size:
2827
+ # doc and dict didn't change => names already cached
2828
+ return 0
2829
+ self._tag_count = 0
2830
+ if not self._py_tags:
2831
+ self._cached_doc = doc
2832
+ self._cached_size = dict_size
2833
+ return 0
2834
+ if not self._cached_tags:
2835
+ self._cached_tags = <qname*>python.lxml_malloc(len(self._py_tags), sizeof(qname))
2836
+ if not self._cached_tags:
2837
+ self._cached_doc = None
2838
+ raise MemoryError()
2839
+ self._tag_count = <size_t>_mapTagsToQnameMatchArray(
2840
+ doc._c_doc, self._py_tags, self._cached_tags, force_into_dict)
2841
+ self._cached_doc = doc
2842
+ self._cached_size = dict_size
2843
+ return 0
2844
+
2845
+ cdef inline bint matches(self, xmlNode* c_node) noexcept:
2846
+ cdef qname* c_qname
2847
+ if self._node_types & (1 << c_node.type):
2848
+ return True
2849
+ elif c_node.type == tree.XML_ELEMENT_NODE:
2850
+ for c_qname in self._cached_tags[:self._tag_count]:
2851
+ if _tagMatchesExactly(c_node, c_qname):
2852
+ return True
2853
+ return False
2854
+
2855
+ cdef inline bint matchesNsTag(self, const_xmlChar* c_href,
2856
+ const_xmlChar* c_name) noexcept:
2857
+ cdef qname* c_qname
2858
+ if self._node_types & (1 << tree.XML_ELEMENT_NODE):
2859
+ return True
2860
+ for c_qname in self._cached_tags[:self._tag_count]:
2861
+ if _nsTagMatchesExactly(c_href, c_name, c_qname):
2862
+ return True
2863
+ return False
2864
+
2865
+ cdef inline bint matchesAttribute(self, xmlAttr* c_attr) noexcept:
2866
+ """Attribute matches differ from Element matches in that they do
2867
+ not care about node types.
2868
+ """
2869
+ cdef qname* c_qname
2870
+ for c_qname in self._cached_tags[:self._tag_count]:
2871
+ if _tagMatchesExactly(<xmlNode*>c_attr, c_qname):
2872
+ return True
2873
+ return False
2874
+
2875
+ cdef class _ElementMatchIterator:
2876
+ cdef _Element _node
2877
+ cdef _node_to_node_function _next_element
2878
+ cdef _MultiTagMatcher _matcher
2879
+
2880
+ @cython.final
2881
+ cdef _initTagMatcher(self, tags):
2882
+ self._matcher = _MultiTagMatcher.__new__(_MultiTagMatcher, tags)
2883
+
2884
+ def __iter__(self):
2885
+ return self
2886
+
2887
+ @cython.final
2888
+ cdef int _storeNext(self, _Element node) except -1:
2889
+ self._matcher.cacheTags(node._doc)
2890
+ c_node = self._next_element(node._c_node)
2891
+ while c_node is not NULL and not self._matcher.matches(c_node):
2892
+ c_node = self._next_element(c_node)
2893
+ # store Python ref to next node to make sure it's kept alive
2894
+ self._node = _elementFactory(node._doc, c_node) if c_node is not NULL else None
2895
+ return 0
2896
+
2897
+ def __next__(self):
2898
+ cdef _Element current_node = self._node
2899
+ if current_node is None:
2900
+ raise StopIteration
2901
+ self._storeNext(current_node)
2902
+ return current_node
2903
+
2904
+ cdef class ElementChildIterator(_ElementMatchIterator):
2905
+ """ElementChildIterator(self, node, tag=None, reversed=False)
2906
+ Iterates over the children of an element.
2907
+ """
2908
+ def __cinit__(self, _Element node not None, tag=None, *, bint reversed=False):
2909
+ cdef xmlNode* c_node
2910
+ _assertValidNode(node)
2911
+ self._initTagMatcher(tag)
2912
+ if reversed:
2913
+ c_node = _findChildBackwards(node._c_node, 0)
2914
+ self._next_element = _previousElement
2915
+ else:
2916
+ c_node = _findChildForwards(node._c_node, 0)
2917
+ self._next_element = _nextElement
2918
+ self._matcher.cacheTags(node._doc)
2919
+ while c_node is not NULL and not self._matcher.matches(c_node):
2920
+ c_node = self._next_element(c_node)
2921
+ # store Python ref to next node to make sure it's kept alive
2922
+ self._node = _elementFactory(node._doc, c_node) if c_node is not NULL else None
2923
+
2924
+ cdef class SiblingsIterator(_ElementMatchIterator):
2925
+ """SiblingsIterator(self, node, tag=None, preceding=False)
2926
+ Iterates over the siblings of an element.
2927
+
2928
+ You can pass the boolean keyword ``preceding`` to specify the direction.
2929
+ """
2930
+ def __cinit__(self, _Element node not None, tag=None, *, bint preceding=False):
2931
+ _assertValidNode(node)
2932
+ self._initTagMatcher(tag)
2933
+ if preceding:
2934
+ self._next_element = _previousElement
2935
+ else:
2936
+ self._next_element = _nextElement
2937
+ self._storeNext(node)
2938
+
2939
+ cdef class AncestorsIterator(_ElementMatchIterator):
2940
+ """AncestorsIterator(self, node, tag=None)
2941
+ Iterates over the ancestors of an element (from parent to parent).
2942
+ """
2943
+ def __cinit__(self, _Element node not None, tag=None):
2944
+ _assertValidNode(node)
2945
+ self._initTagMatcher(tag)
2946
+ self._next_element = _parentElement
2947
+ self._storeNext(node)
2948
+
2949
+ cdef class ElementDepthFirstIterator:
2950
+ """ElementDepthFirstIterator(self, node, tag=None, inclusive=True)
2951
+ Iterates over an element and its sub-elements in document order (depth
2952
+ first pre-order).
2953
+
2954
+ Note that this also includes comments, entities and processing
2955
+ instructions. To filter them out, check if the ``tag`` property
2956
+ of the returned element is a string (i.e. not None and not a
2957
+ factory function), or pass the ``Element`` factory for the ``tag``
2958
+ argument to receive only Elements.
2959
+
2960
+ If the optional ``tag`` argument is not None, the iterator returns only
2961
+ the elements that match the respective name and namespace.
2962
+
2963
+ The optional boolean argument 'inclusive' defaults to True and can be set
2964
+ to False to exclude the start element itself.
2965
+
2966
+ Note that the behaviour of this iterator is completely undefined if the
2967
+ tree it traverses is modified during iteration.
2968
+ """
2969
+ # we keep Python references here to control GC
2970
+ # keep the next Element after the one we return, and the (s)top node
2971
+ cdef _Element _next_node
2972
+ cdef _Element _top_node
2973
+ cdef _MultiTagMatcher _matcher
2974
+ def __cinit__(self, _Element node not None, tag=None, *, bint inclusive=True):
2975
+ _assertValidNode(node)
2976
+ self._top_node = node
2977
+ self._next_node = node
2978
+ self._matcher = _MultiTagMatcher.__new__(_MultiTagMatcher, tag)
2979
+ self._matcher.cacheTags(node._doc)
2980
+ if not inclusive or not self._matcher.matches(node._c_node):
2981
+ # find start node (this cannot raise StopIteration, self._next_node != None)
2982
+ next(self)
2983
+
2984
+ def __iter__(self):
2985
+ return self
2986
+
2987
+ def __next__(self):
2988
+ cdef xmlNode* c_node
2989
+ cdef _Element current_node = self._next_node
2990
+ if current_node is None:
2991
+ raise StopIteration
2992
+ c_node = current_node._c_node
2993
+ self._matcher.cacheTags(current_node._doc)
2994
+ if not self._matcher._tag_count:
2995
+ # no tag name was found in the dict => not in document either
2996
+ # try to match by node type
2997
+ c_node = self._nextNodeAnyTag(c_node)
2998
+ else:
2999
+ c_node = self._nextNodeMatchTag(c_node)
3000
+ if c_node is NULL:
3001
+ self._next_node = None
3002
+ else:
3003
+ self._next_node = _elementFactory(current_node._doc, c_node)
3004
+ return current_node
3005
+
3006
+ @cython.final
3007
+ cdef xmlNode* _nextNodeAnyTag(self, xmlNode* c_node) noexcept:
3008
+ cdef int node_types = self._matcher._node_types
3009
+ if not node_types:
3010
+ return NULL
3011
+ tree.BEGIN_FOR_EACH_ELEMENT_FROM(self._top_node._c_node, c_node, 0)
3012
+ if node_types & (1 << c_node.type):
3013
+ return c_node
3014
+ tree.END_FOR_EACH_ELEMENT_FROM(c_node)
3015
+ return NULL
3016
+
3017
+ @cython.final
3018
+ cdef xmlNode* _nextNodeMatchTag(self, xmlNode* c_node) noexcept:
3019
+ tree.BEGIN_FOR_EACH_ELEMENT_FROM(self._top_node._c_node, c_node, 0)
3020
+ if self._matcher.matches(c_node):
3021
+ return c_node
3022
+ tree.END_FOR_EACH_ELEMENT_FROM(c_node)
3023
+ return NULL
3024
+
3025
+
3026
+ cdef class ElementTextIterator:
3027
+ """ElementTextIterator(self, element, tag=None, with_tail=True)
3028
+ Iterates over the text content of a subtree.
3029
+
3030
+ You can pass the ``tag`` keyword argument to restrict text content to a
3031
+ specific tag name.
3032
+
3033
+ You can set the ``with_tail`` keyword argument to ``False`` to skip over
3034
+ tail text (e.g. if you know that it's only whitespace from pretty-printing).
3035
+ """
3036
+ cdef object _events
3037
+ cdef _Element _start_element
3038
+ def __cinit__(self, _Element element not None, tag=None, *, bint with_tail=True):
3039
+ _assertValidNode(element)
3040
+ if with_tail:
3041
+ events = ("start", "comment", "pi", "end")
3042
+ else:
3043
+ events = ("start",)
3044
+ self._start_element = element
3045
+ self._events = iterwalk(element, events=events, tag=tag)
3046
+
3047
+ def __iter__(self):
3048
+ return self
3049
+
3050
+ def __next__(self):
3051
+ cdef _Element element
3052
+ result = None
3053
+ while result is None:
3054
+ event, element = next(self._events) # raises StopIteration
3055
+ if event == "start":
3056
+ result = element.text
3057
+ elif element is not self._start_element:
3058
+ result = element.tail
3059
+ return result
3060
+
3061
+
3062
+ cdef xmlNode* _createElement(xmlDoc* c_doc, object name_utf) except NULL:
3063
+ cdef xmlNode* c_node
3064
+ c_node = tree.xmlNewDocNode(c_doc, NULL, _xcstr(name_utf), NULL)
3065
+ return c_node
3066
+
3067
+ cdef xmlNode* _createComment(xmlDoc* c_doc, const_xmlChar* text) noexcept:
3068
+ cdef xmlNode* c_node
3069
+ c_node = tree.xmlNewDocComment(c_doc, text)
3070
+ return c_node
3071
+
3072
+ cdef xmlNode* _createPI(xmlDoc* c_doc, const_xmlChar* target, const_xmlChar* text) noexcept:
3073
+ cdef xmlNode* c_node
3074
+ c_node = tree.xmlNewDocPI(c_doc, target, text)
3075
+ return c_node
3076
+
3077
+ cdef xmlNode* _createEntity(xmlDoc* c_doc, const_xmlChar* name) noexcept:
3078
+ cdef xmlNode* c_node
3079
+ c_node = tree.xmlNewReference(c_doc, name)
3080
+ return c_node
3081
+
3082
+ # module-level API for ElementTree
3083
+
3084
+ def Element(_tag, attrib=None, nsmap=None, **_extra):
3085
+ """Element(_tag, attrib=None, nsmap=None, **_extra)
3086
+
3087
+ Element factory. This function returns an object implementing the
3088
+ Element interface.
3089
+
3090
+ Also look at the `_Element.makeelement()` and
3091
+ `_BaseParser.makeelement()` methods, which provide a faster way to
3092
+ create an Element within a specific document or parser context.
3093
+ """
3094
+ return _makeElement(_tag, NULL, None, None, None, None,
3095
+ attrib, nsmap, _extra)
3096
+
3097
+
3098
+ def Comment(text=None):
3099
+ """Comment(text=None)
3100
+
3101
+ Comment element factory. This factory function creates a special element that will
3102
+ be serialized as an XML comment.
3103
+ """
3104
+ cdef _Document doc
3105
+ cdef xmlNode* c_node
3106
+ cdef xmlDoc* c_doc
3107
+
3108
+ if text is None:
3109
+ text = b''
3110
+ else:
3111
+ text = _utf8(text)
3112
+ if b'--' in text or text.endswith(b'-'):
3113
+ raise ValueError("Comment may not contain '--' or end with '-'")
3114
+
3115
+ c_doc = _newXMLDoc()
3116
+ doc = _documentFactory(c_doc, None)
3117
+ c_node = _createComment(c_doc, _xcstr(text))
3118
+ tree.xmlAddChild(<xmlNode*>c_doc, c_node)
3119
+ return _elementFactory(doc, c_node)
3120
+
3121
+
3122
+ def ProcessingInstruction(target, text=None):
3123
+ """ProcessingInstruction(target, text=None)
3124
+
3125
+ ProcessingInstruction element factory. This factory function creates a
3126
+ special element that will be serialized as an XML processing instruction.
3127
+ """
3128
+ cdef _Document doc
3129
+ cdef xmlNode* c_node
3130
+ cdef xmlDoc* c_doc
3131
+
3132
+ target = _utf8(target)
3133
+ _tagValidOrRaise(target)
3134
+ if target.lower() == b'xml':
3135
+ raise ValueError, f"Invalid PI name '{target}'"
3136
+
3137
+ if text is None:
3138
+ text = b''
3139
+ else:
3140
+ text = _utf8(text)
3141
+ if b'?>' in text:
3142
+ raise ValueError, "PI text must not contain '?>'"
3143
+
3144
+ c_doc = _newXMLDoc()
3145
+ doc = _documentFactory(c_doc, None)
3146
+ c_node = _createPI(c_doc, _xcstr(target), _xcstr(text))
3147
+ tree.xmlAddChild(<xmlNode*>c_doc, c_node)
3148
+ return _elementFactory(doc, c_node)
3149
+
3150
+ PI = ProcessingInstruction
3151
+
3152
+
3153
+ cdef class CDATA:
3154
+ """CDATA(data)
3155
+
3156
+ CDATA factory. This factory creates an opaque data object that
3157
+ can be used to set Element text. The usual way to use it is::
3158
+
3159
+ >>> el = Element('content')
3160
+ >>> el.text = CDATA('a string')
3161
+
3162
+ >>> print(el.text)
3163
+ a string
3164
+ >>> print(tostring(el, encoding="unicode"))
3165
+ <content><![CDATA[a string]]></content>
3166
+ """
3167
+ cdef bytes _utf8_data
3168
+ def __cinit__(self, data):
3169
+ self._utf8_data = _utf8(data)
3170
+
3171
+
3172
+ def Entity(name):
3173
+ """Entity(name)
3174
+
3175
+ Entity factory. This factory function creates a special element
3176
+ that will be serialized as an XML entity reference or character
3177
+ reference. Note, however, that entities will not be automatically
3178
+ declared in the document. A document that uses entity references
3179
+ requires a DTD to define the entities.
3180
+ """
3181
+ cdef _Document doc
3182
+ cdef xmlNode* c_node
3183
+ cdef xmlDoc* c_doc
3184
+ name_utf = _utf8(name)
3185
+ c_name = _xcstr(name_utf)
3186
+ if c_name[0] == c'#':
3187
+ if not _characterReferenceIsValid(c_name + 1):
3188
+ raise ValueError, f"Invalid character reference: '{name}'"
3189
+ elif not _xmlNameIsValid(c_name):
3190
+ raise ValueError, f"Invalid entity reference: '{name}'"
3191
+ c_doc = _newXMLDoc()
3192
+ doc = _documentFactory(c_doc, None)
3193
+ c_node = _createEntity(c_doc, c_name)
3194
+ tree.xmlAddChild(<xmlNode*>c_doc, c_node)
3195
+ return _elementFactory(doc, c_node)
3196
+
3197
+
3198
+ def SubElement(_Element _parent not None, _tag,
3199
+ attrib=None, nsmap=None, **_extra):
3200
+ """SubElement(_parent, _tag, attrib=None, nsmap=None, **_extra)
3201
+
3202
+ Subelement factory. This function creates an element instance, and
3203
+ appends it to an existing element.
3204
+ """
3205
+ return _makeSubElement(_parent, _tag, None, None, attrib, nsmap, _extra)
3206
+
3207
+
3208
+ def ElementTree(_Element element=None, *, file=None, _BaseParser parser=None):
3209
+ """ElementTree(element=None, file=None, parser=None)
3210
+
3211
+ ElementTree wrapper class.
3212
+ """
3213
+ cdef xmlNode* c_next
3214
+ cdef xmlNode* c_node
3215
+ cdef xmlNode* c_node_copy
3216
+ cdef xmlDoc* c_doc
3217
+ cdef _ElementTree etree
3218
+ cdef _Document doc
3219
+
3220
+ if element is not None:
3221
+ doc = element._doc
3222
+ elif file is not None:
3223
+ try:
3224
+ doc = _parseDocument(file, parser, None)
3225
+ except _TargetParserResult as result_container:
3226
+ return result_container.result
3227
+ else:
3228
+ c_doc = _newXMLDoc()
3229
+ doc = _documentFactory(c_doc, parser)
3230
+
3231
+ return _elementTreeFactory(doc, element)
3232
+
3233
+
3234
+ def HTML(text, _BaseParser parser=None, *, base_url=None):
3235
+ """HTML(text, parser=None, base_url=None)
3236
+
3237
+ Parses an HTML document from a string constant. Returns the root
3238
+ node (or the result returned by a parser target). This function
3239
+ can be used to embed "HTML literals" in Python code.
3240
+
3241
+ To override the parser with a different ``HTMLParser`` you can pass it to
3242
+ the ``parser`` keyword argument.
3243
+
3244
+ The ``base_url`` keyword argument allows to set the original base URL of
3245
+ the document to support relative Paths when looking up external entities
3246
+ (DTD, XInclude, ...).
3247
+ """
3248
+ cdef _Document doc
3249
+ if parser is None:
3250
+ parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
3251
+ if not isinstance(parser, HTMLParser):
3252
+ parser = __DEFAULT_HTML_PARSER
3253
+ try:
3254
+ doc = _parseMemoryDocument(text, base_url, parser)
3255
+ return doc.getroot()
3256
+ except _TargetParserResult as result_container:
3257
+ return result_container.result
3258
+
3259
+
3260
+ def XML(text, _BaseParser parser=None, *, base_url=None):
3261
+ """XML(text, parser=None, base_url=None)
3262
+
3263
+ Parses an XML document or fragment from a string constant.
3264
+ Returns the root node (or the result returned by a parser target).
3265
+ This function can be used to embed "XML literals" in Python code,
3266
+ like in
3267
+
3268
+ >>> root = XML("<root><test/></root>")
3269
+ >>> print(root.tag)
3270
+ root
3271
+
3272
+ To override the parser with a different ``XMLParser`` you can pass it to
3273
+ the ``parser`` keyword argument.
3274
+
3275
+ The ``base_url`` keyword argument allows to set the original base URL of
3276
+ the document to support relative Paths when looking up external entities
3277
+ (DTD, XInclude, ...).
3278
+ """
3279
+ cdef _Document doc
3280
+ if parser is None:
3281
+ parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
3282
+ if not isinstance(parser, XMLParser):
3283
+ parser = __DEFAULT_XML_PARSER
3284
+ try:
3285
+ doc = _parseMemoryDocument(text, base_url, parser)
3286
+ return doc.getroot()
3287
+ except _TargetParserResult as result_container:
3288
+ return result_container.result
3289
+
3290
+
3291
+ def fromstring(text, _BaseParser parser=None, *, base_url=None):
3292
+ """fromstring(text, parser=None, base_url=None)
3293
+
3294
+ Parses an XML document or fragment from a string. Returns the
3295
+ root node (or the result returned by a parser target).
3296
+
3297
+ To override the default parser with a different parser you can pass it to
3298
+ the ``parser`` keyword argument.
3299
+
3300
+ The ``base_url`` keyword argument allows to set the original base URL of
3301
+ the document to support relative Paths when looking up external entities
3302
+ (DTD, XInclude, ...).
3303
+ """
3304
+ cdef _Document doc
3305
+ try:
3306
+ doc = _parseMemoryDocument(text, base_url, parser)
3307
+ return doc.getroot()
3308
+ except _TargetParserResult as result_container:
3309
+ return result_container.result
3310
+
3311
+
3312
+ def fromstringlist(strings, _BaseParser parser=None):
3313
+ """fromstringlist(strings, parser=None)
3314
+
3315
+ Parses an XML document from a sequence of strings. Returns the
3316
+ root node (or the result returned by a parser target).
3317
+
3318
+ To override the default parser with a different parser you can pass it to
3319
+ the ``parser`` keyword argument.
3320
+ """
3321
+ cdef _Document doc
3322
+ if isinstance(strings, (bytes, unicode)):
3323
+ raise ValueError("passing a single string into fromstringlist() is not"
3324
+ " efficient, use fromstring() instead")
3325
+ if parser is None:
3326
+ parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
3327
+ feed = parser.feed
3328
+ for data in strings:
3329
+ feed(data)
3330
+ return parser.close()
3331
+
3332
+
3333
+ def iselement(element):
3334
+ """iselement(element)
3335
+
3336
+ Checks if an object appears to be a valid element object.
3337
+ """
3338
+ return isinstance(element, _Element) and (<_Element>element)._c_node is not NULL
3339
+
3340
+
3341
+ def indent(tree, space=" ", *, Py_ssize_t level=0):
3342
+ """indent(tree, space=" ", level=0)
3343
+
3344
+ Indent an XML document by inserting newlines and indentation space
3345
+ after elements.
3346
+
3347
+ *tree* is the ElementTree or Element to modify. The (root) element
3348
+ itself will not be changed, but the tail text of all elements in its
3349
+ subtree will be adapted.
3350
+
3351
+ *space* is the whitespace to insert for each indentation level, two
3352
+ space characters by default.
3353
+
3354
+ *level* is the initial indentation level. Setting this to a higher
3355
+ value than 0 can be used for indenting subtrees that are more deeply
3356
+ nested inside of a document.
3357
+ """
3358
+ root = _rootNodeOrRaise(tree)
3359
+ if level < 0:
3360
+ raise ValueError(f"Initial indentation level must be >= 0, got {level}")
3361
+ if _hasChild(root._c_node):
3362
+ space = _utf8(space)
3363
+ indent = b"\n" + level * space
3364
+ _indent_children(root._c_node, 1, space, [indent, indent + space])
3365
+
3366
+
3367
+ cdef int _indent_children(xmlNode* c_node, Py_ssize_t level, bytes one_space, list indentations) except -1:
3368
+ # Reuse indentation strings for speed.
3369
+ if len(indentations) <= level:
3370
+ indentations.append(indentations[-1] + one_space)
3371
+
3372
+ # Start a new indentation level for the first child.
3373
+ child_indentation = indentations[level]
3374
+ if not _hasNonWhitespaceText(c_node):
3375
+ _setNodeText(c_node, child_indentation)
3376
+
3377
+ # Recursively indent all children.
3378
+ cdef xmlNode* c_child = _findChildForwards(c_node, 0)
3379
+ while c_child is not NULL:
3380
+ if _hasChild(c_child):
3381
+ _indent_children(c_child, level+1, one_space, indentations)
3382
+ c_next_child = _nextElement(c_child)
3383
+ if not _hasNonWhitespaceTail(c_child):
3384
+ if c_next_child is NULL:
3385
+ # Dedent after the last child.
3386
+ child_indentation = indentations[level-1]
3387
+ _setTailText(c_child, child_indentation)
3388
+ c_child = c_next_child
3389
+ return 0
3390
+
3391
+
3392
+ def dump(_Element elem not None, *, bint pretty_print=True, bint with_tail=True):
3393
+ """dump(elem, pretty_print=True, with_tail=True)
3394
+
3395
+ Writes an element tree or element structure to sys.stdout. This function
3396
+ should be used for debugging only.
3397
+ """
3398
+ xml = tostring(elem, pretty_print=pretty_print, with_tail=with_tail, encoding='unicode')
3399
+ if not pretty_print:
3400
+ xml += '\n'
3401
+ sys.stdout.write(xml)
3402
+
3403
+
3404
+ def tostring(element_or_tree, *, encoding=None, method="xml",
3405
+ xml_declaration=None, bint pretty_print=False, bint with_tail=True,
3406
+ standalone=None, doctype=None,
3407
+ # method='c14n'
3408
+ bint exclusive=False, inclusive_ns_prefixes=None,
3409
+ # method='c14n2'
3410
+ bint with_comments=True, bint strip_text=False,
3411
+ ):
3412
+ """tostring(element_or_tree, encoding=None, method="xml",
3413
+ xml_declaration=None, pretty_print=False, with_tail=True,
3414
+ standalone=None, doctype=None,
3415
+ exclusive=False, inclusive_ns_prefixes=None,
3416
+ with_comments=True, strip_text=False,
3417
+ )
3418
+
3419
+ Serialize an element to an encoded string representation of its XML
3420
+ tree.
3421
+
3422
+ Defaults to ASCII encoding without XML declaration. This
3423
+ behaviour can be configured with the keyword arguments 'encoding'
3424
+ (string) and 'xml_declaration' (bool). Note that changing the
3425
+ encoding to a non UTF-8 compatible encoding will enable a
3426
+ declaration by default.
3427
+
3428
+ You can also serialise to a Unicode string without declaration by
3429
+ passing the name ``'unicode'`` as encoding (or the ``str`` function
3430
+ in Py3 or ``unicode`` in Py2). This changes the return value from
3431
+ a byte string to an unencoded unicode string.
3432
+
3433
+ The keyword argument 'pretty_print' (bool) enables formatted XML.
3434
+
3435
+ The keyword argument 'method' selects the output method: 'xml',
3436
+ 'html', plain 'text' (text content without tags), 'c14n' or 'c14n2'.
3437
+ Default is 'xml'.
3438
+
3439
+ With ``method="c14n"`` (C14N version 1), the options ``exclusive``,
3440
+ ``with_comments`` and ``inclusive_ns_prefixes`` request exclusive
3441
+ C14N, include comments, and list the inclusive prefixes respectively.
3442
+
3443
+ With ``method="c14n2"`` (C14N version 2), the ``with_comments`` and
3444
+ ``strip_text`` options control the output of comments and text space
3445
+ according to C14N 2.0.
3446
+
3447
+ Passing a boolean value to the ``standalone`` option will output
3448
+ an XML declaration with the corresponding ``standalone`` flag.
3449
+
3450
+ The ``doctype`` option allows passing in a plain string that will
3451
+ be serialised before the XML tree. Note that passing in non
3452
+ well-formed content here will make the XML output non well-formed.
3453
+ Also, an existing doctype in the document tree will not be removed
3454
+ when serialising an ElementTree instance.
3455
+
3456
+ You can prevent the tail text of the element from being serialised
3457
+ by passing the boolean ``with_tail`` option. This has no impact
3458
+ on the tail text of children, which will always be serialised.
3459
+ """
3460
+ cdef bint write_declaration
3461
+ cdef int is_standalone
3462
+ # C14N serialisation
3463
+ if method in ('c14n', 'c14n2'):
3464
+ if encoding is not None:
3465
+ raise ValueError("Cannot specify encoding with C14N")
3466
+ if xml_declaration:
3467
+ raise ValueError("Cannot enable XML declaration in C14N")
3468
+ if method == 'c14n':
3469
+ return _tostringC14N(element_or_tree, exclusive, with_comments, inclusive_ns_prefixes)
3470
+ else:
3471
+ out = BytesIO()
3472
+ target = C14NWriterTarget(
3473
+ utf8_writer(out).write,
3474
+ with_comments=with_comments, strip_text=strip_text)
3475
+ _tree_to_target(element_or_tree, target)
3476
+ return out.getvalue()
3477
+ if not with_comments:
3478
+ raise ValueError("Can only discard comments in C14N serialisation")
3479
+ if strip_text:
3480
+ raise ValueError("Can only strip text in C14N 2.0 serialisation")
3481
+ if encoding is unicode or (encoding is not None and encoding.lower() == 'unicode'):
3482
+ if xml_declaration:
3483
+ raise ValueError, \
3484
+ "Serialisation to unicode must not request an XML declaration"
3485
+ write_declaration = 0
3486
+ encoding = unicode
3487
+ elif xml_declaration is None:
3488
+ # by default, write an XML declaration only for non-standard encodings
3489
+ write_declaration = encoding is not None and encoding.upper() not in \
3490
+ ('ASCII', 'UTF-8', 'UTF8', 'US-ASCII')
3491
+ else:
3492
+ write_declaration = xml_declaration
3493
+ if encoding is None:
3494
+ encoding = 'ASCII'
3495
+ if standalone is None:
3496
+ is_standalone = -1
3497
+ elif standalone:
3498
+ write_declaration = 1
3499
+ is_standalone = 1
3500
+ else:
3501
+ write_declaration = 1
3502
+ is_standalone = 0
3503
+
3504
+ if isinstance(element_or_tree, _Element):
3505
+ return _tostring(<_Element>element_or_tree, encoding, doctype, method,
3506
+ write_declaration, 0, pretty_print, with_tail,
3507
+ is_standalone)
3508
+ elif isinstance(element_or_tree, _ElementTree):
3509
+ return _tostring((<_ElementTree>element_or_tree)._context_node,
3510
+ encoding, doctype, method, write_declaration, 1,
3511
+ pretty_print, with_tail, is_standalone)
3512
+ else:
3513
+ raise TypeError, f"Type '{python._fqtypename(element_or_tree).decode('utf8')}' cannot be serialized."
3514
+
3515
+
3516
+
3517
+ def tostringlist(element_or_tree, *args, **kwargs):
3518
+ """tostringlist(element_or_tree, *args, **kwargs)
3519
+
3520
+ Serialize an element to an encoded string representation of its XML
3521
+ tree, stored in a list of partial strings.
3522
+
3523
+ This is purely for ElementTree 1.3 compatibility. The result is a
3524
+ single string wrapped in a list.
3525
+ """
3526
+ return [tostring(element_or_tree, *args, **kwargs)]
3527
+
3528
+
3529
+ def tounicode(element_or_tree, *, method="xml", bint pretty_print=False,
3530
+ bint with_tail=True, doctype=None):
3531
+ """tounicode(element_or_tree, method="xml", pretty_print=False,
3532
+ with_tail=True, doctype=None)
3533
+
3534
+ Serialize an element to the Python unicode representation of its XML
3535
+ tree.
3536
+
3537
+ :deprecated: use ``tostring(el, encoding='unicode')`` instead.
3538
+
3539
+ Note that the result does not carry an XML encoding declaration and is
3540
+ therefore not necessarily suited for serialization to byte streams without
3541
+ further treatment.
3542
+
3543
+ The boolean keyword argument 'pretty_print' enables formatted XML.
3544
+
3545
+ The keyword argument 'method' selects the output method: 'xml',
3546
+ 'html' or plain 'text'.
3547
+
3548
+ You can prevent the tail text of the element from being serialised
3549
+ by passing the boolean ``with_tail`` option. This has no impact
3550
+ on the tail text of children, which will always be serialised.
3551
+ """
3552
+ if isinstance(element_or_tree, _Element):
3553
+ return _tostring(<_Element>element_or_tree, unicode, doctype, method,
3554
+ 0, 0, pretty_print, with_tail, -1)
3555
+ elif isinstance(element_or_tree, _ElementTree):
3556
+ return _tostring((<_ElementTree>element_or_tree)._context_node,
3557
+ unicode, doctype, method, 0, 1, pretty_print,
3558
+ with_tail, -1)
3559
+ else:
3560
+ raise TypeError, f"Type '{type(element_or_tree)}' cannot be serialized."
3561
+
3562
+
3563
+ def parse(source, _BaseParser parser=None, *, base_url=None):
3564
+ """parse(source, parser=None, base_url=None)
3565
+
3566
+ Return an ElementTree object loaded with source elements. If no parser
3567
+ is provided as second argument, the default parser is used.
3568
+
3569
+ The ``source`` can be any of the following:
3570
+
3571
+ - a file name/path
3572
+ - a file object
3573
+ - a file-like object
3574
+ - a URL using the HTTP or FTP protocol
3575
+
3576
+ To parse from a string, use the ``fromstring()`` function instead.
3577
+
3578
+ Note that it is generally faster to parse from a file path or URL
3579
+ than from an open file object or file-like object. Transparent
3580
+ decompression from gzip compressed sources is supported (unless
3581
+ explicitly disabled in libxml2).
3582
+
3583
+ The ``base_url`` keyword allows setting a URL for the document
3584
+ when parsing from a file-like object. This is needed when looking
3585
+ up external entities (DTD, XInclude, ...) with relative paths.
3586
+ """
3587
+ cdef _Document doc
3588
+ try:
3589
+ doc = _parseDocument(source, parser, base_url)
3590
+ return _elementTreeFactory(doc, None)
3591
+ except _TargetParserResult as result_container:
3592
+ return result_container.result
3593
+
3594
+
3595
+ def adopt_external_document(capsule, _BaseParser parser=None):
3596
+ """adopt_external_document(capsule, parser=None)
3597
+
3598
+ Unpack a libxml2 document pointer from a PyCapsule and wrap it in an
3599
+ lxml ElementTree object.
3600
+
3601
+ This allows external libraries to build XML/HTML trees using libxml2
3602
+ and then pass them efficiently into lxml for further processing.
3603
+
3604
+ If a ``parser`` is provided, it will be used for configuring the
3605
+ lxml document. No parsing will be done.
3606
+
3607
+ The capsule must have the name ``"libxml2:xmlDoc"`` and its pointer
3608
+ value must reference a correct libxml2 document of type ``xmlDoc*``.
3609
+ The creator of the capsule must take care to correctly clean up the
3610
+ document using an appropriate capsule destructor. By default, the
3611
+ libxml2 document will be copied to let lxml safely own the memory
3612
+ of the internal tree that it uses.
3613
+
3614
+ If the capsule context is non-NULL, it must point to a C string that
3615
+ can be compared using ``strcmp()``. If the context string equals
3616
+ ``"destructor:xmlFreeDoc"``, the libxml2 document will not be copied
3617
+ but the capsule invalidated instead by clearing its destructor and
3618
+ name. That way, lxml takes ownership of the libxml2 document in memory
3619
+ without creating a copy first, and the capsule destructor will not be
3620
+ called. The document will then eventually be cleaned up by lxml using
3621
+ the libxml2 API function ``xmlFreeDoc()`` once it is no longer used.
3622
+
3623
+ If no copy is made, later modifications of the tree outside of lxml
3624
+ should not be attempted after transferring the ownership.
3625
+ """
3626
+ cdef xmlDoc* c_doc
3627
+ cdef bint is_owned = False
3628
+ c_doc = <xmlDoc*> python.lxml_unpack_xmldoc_capsule(capsule, &is_owned)
3629
+ doc = _adoptForeignDoc(c_doc, parser, is_owned)
3630
+ return _elementTreeFactory(doc, None)
3631
+
3632
+
3633
+ ################################################################################
3634
+ # Include submodules
3635
+
3636
+ include "readonlytree.pxi" # Read-only implementation of Element proxies
3637
+ include "classlookup.pxi" # Element class lookup mechanisms
3638
+ include "nsclasses.pxi" # Namespace implementation and registry
3639
+ include "docloader.pxi" # Support for custom document loaders
3640
+ include "parser.pxi" # XML and HTML parsers
3641
+ include "saxparser.pxi" # SAX-like Parser interface and tree builder
3642
+ include "parsertarget.pxi" # ET Parser target
3643
+ include "serializer.pxi" # XML output functions
3644
+ include "iterparse.pxi" # incremental XML parsing
3645
+ include "xmlid.pxi" # XMLID and IDDict
3646
+ include "xinclude.pxi" # XInclude
3647
+ include "cleanup.pxi" # Cleanup and recursive element removal functions
3648
+
3649
+
3650
+ ################################################################################
3651
+ # Include submodules for XPath and XSLT
3652
+
3653
+ include "extensions.pxi" # XPath/XSLT extension functions
3654
+ include "xpath.pxi" # XPath evaluation
3655
+ include "xslt.pxi" # XSL transformations
3656
+ include "xsltext.pxi" # XSL extension elements
3657
+
3658
+
3659
+ ################################################################################
3660
+ # Validation
3661
+
3662
+ cdef class DocumentInvalid(LxmlError):
3663
+ """Validation error.
3664
+
3665
+ Raised by all document validators when their ``assertValid(tree)``
3666
+ method fails.
3667
+ """
3668
+
3669
+
3670
+ cdef class _Validator:
3671
+ "Base class for XML validators."
3672
+ cdef _ErrorLog _error_log
3673
+ def __cinit__(self):
3674
+ self._error_log = _ErrorLog()
3675
+
3676
+ def validate(self, etree):
3677
+ """validate(self, etree)
3678
+
3679
+ Validate the document using this schema.
3680
+
3681
+ Returns true if document is valid, false if not.
3682
+ """
3683
+ return self(etree)
3684
+
3685
+ def assertValid(self, etree):
3686
+ """assertValid(self, etree)
3687
+
3688
+ Raises `DocumentInvalid` if the document does not comply with the schema.
3689
+ """
3690
+ if not self(etree):
3691
+ raise DocumentInvalid(self._error_log._buildExceptionMessage(
3692
+ "Document does not comply with schema"),
3693
+ self._error_log)
3694
+
3695
+ def assert_(self, etree):
3696
+ """assert_(self, etree)
3697
+
3698
+ Raises `AssertionError` if the document does not comply with the schema.
3699
+ """
3700
+ if not self(etree):
3701
+ raise AssertionError, self._error_log._buildExceptionMessage(
3702
+ "Document does not comply with schema")
3703
+
3704
+ cpdef _append_log_message(self, int domain, int type, int level, int line,
3705
+ message, filename):
3706
+ self._error_log._receiveGeneric(domain, type, level, line, message,
3707
+ filename)
3708
+
3709
+ cpdef _clear_error_log(self):
3710
+ self._error_log.clear()
3711
+
3712
+ @property
3713
+ def error_log(self):
3714
+ """The log of validation errors and warnings."""
3715
+ assert self._error_log is not None, "XPath evaluator not initialised"
3716
+ return self._error_log.copy()
3717
+
3718
+ include "dtd.pxi" # DTD
3719
+ include "relaxng.pxi" # RelaxNG
3720
+ include "xmlschema.pxi" # XMLSchema
3721
+ include "schematron.pxi" # Schematron (requires libxml2 2.6.21+)
3722
+
3723
+ ################################################################################
3724
+ # Public C API
3725
+
3726
+ include "public-api.pxi"
3727
+
3728
+ ################################################################################
3729
+ # Other stuff
3730
+
3731
+ include "debug.pxi"