lxml 5.3.2__cp310-cp310-win32.win32.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 (175) hide show
  1. lxml/ElementInclude.py +244 -0
  2. lxml/__init__.py +22 -0
  3. lxml/_elementpath.cp310-win32.pyd +0 -0
  4. lxml/_elementpath.py +341 -0
  5. lxml/apihelpers.pxi +1793 -0
  6. lxml/builder.cp310-win32.pyd +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 +479 -0
  15. lxml/etree.cp310-win32.pyd +0 -0
  16. lxml/etree.h +248 -0
  17. lxml/etree.pyx +3732 -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.cp310-win32.pyd +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/zconf.h +543 -0
  43. lxml/includes/extlibs/zlib.h +1938 -0
  44. lxml/includes/htmlparser.pxd +56 -0
  45. lxml/includes/libexslt/__init__.py +0 -0
  46. lxml/includes/libexslt/exslt.h +108 -0
  47. lxml/includes/libexslt/exsltconfig.h +70 -0
  48. lxml/includes/libexslt/exsltexports.h +63 -0
  49. lxml/includes/libexslt/libexslt.h +29 -0
  50. lxml/includes/libxml/HTMLparser.h +320 -0
  51. lxml/includes/libxml/HTMLtree.h +147 -0
  52. lxml/includes/libxml/SAX.h +204 -0
  53. lxml/includes/libxml/SAX2.h +173 -0
  54. lxml/includes/libxml/__init__.py +0 -0
  55. lxml/includes/libxml/c14n.h +128 -0
  56. lxml/includes/libxml/catalog.h +182 -0
  57. lxml/includes/libxml/chvalid.h +230 -0
  58. lxml/includes/libxml/debugXML.h +217 -0
  59. lxml/includes/libxml/dict.h +81 -0
  60. lxml/includes/libxml/encoding.h +233 -0
  61. lxml/includes/libxml/entities.h +151 -0
  62. lxml/includes/libxml/globals.h +529 -0
  63. lxml/includes/libxml/hash.h +236 -0
  64. lxml/includes/libxml/list.h +137 -0
  65. lxml/includes/libxml/nanoftp.h +186 -0
  66. lxml/includes/libxml/nanohttp.h +81 -0
  67. lxml/includes/libxml/parser.h +1265 -0
  68. lxml/includes/libxml/parserInternals.h +662 -0
  69. lxml/includes/libxml/pattern.h +100 -0
  70. lxml/includes/libxml/relaxng.h +218 -0
  71. lxml/includes/libxml/schemasInternals.h +958 -0
  72. lxml/includes/libxml/schematron.h +142 -0
  73. lxml/includes/libxml/threads.h +94 -0
  74. lxml/includes/libxml/tree.h +1314 -0
  75. lxml/includes/libxml/uri.h +94 -0
  76. lxml/includes/libxml/valid.h +448 -0
  77. lxml/includes/libxml/xinclude.h +129 -0
  78. lxml/includes/libxml/xlink.h +189 -0
  79. lxml/includes/libxml/xmlIO.h +369 -0
  80. lxml/includes/libxml/xmlautomata.h +146 -0
  81. lxml/includes/libxml/xmlerror.h +919 -0
  82. lxml/includes/libxml/xmlexports.h +50 -0
  83. lxml/includes/libxml/xmlmemory.h +228 -0
  84. lxml/includes/libxml/xmlmodule.h +57 -0
  85. lxml/includes/libxml/xmlreader.h +428 -0
  86. lxml/includes/libxml/xmlregexp.h +222 -0
  87. lxml/includes/libxml/xmlsave.h +88 -0
  88. lxml/includes/libxml/xmlschemas.h +246 -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 +526 -0
  93. lxml/includes/libxml/xmlwriter.h +488 -0
  94. lxml/includes/libxml/xpath.h +575 -0
  95. lxml/includes/libxml/xpathInternals.h +632 -0
  96. lxml/includes/libxml/xpointer.h +137 -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/libxslt.h +36 -0
  106. lxml/includes/libxslt/namespaces.h +68 -0
  107. lxml/includes/libxslt/numbersInternals.h +73 -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/trio.h +216 -0
  113. lxml/includes/libxslt/triodef.h +220 -0
  114. lxml/includes/libxslt/variables.h +118 -0
  115. lxml/includes/libxslt/win32config.h +51 -0
  116. lxml/includes/libxslt/xslt.h +110 -0
  117. lxml/includes/libxslt/xsltInternals.h +1992 -0
  118. lxml/includes/libxslt/xsltconfig.h +179 -0
  119. lxml/includes/libxslt/xsltexports.h +64 -0
  120. lxml/includes/libxslt/xsltlocale.h +44 -0
  121. lxml/includes/libxslt/xsltutils.h +343 -0
  122. lxml/includes/lxml-version.h +3 -0
  123. lxml/includes/relaxng.pxd +64 -0
  124. lxml/includes/schematron.pxd +34 -0
  125. lxml/includes/tree.pxd +494 -0
  126. lxml/includes/uri.pxd +5 -0
  127. lxml/includes/xinclude.pxd +22 -0
  128. lxml/includes/xmlerror.pxd +852 -0
  129. lxml/includes/xmlparser.pxd +265 -0
  130. lxml/includes/xmlschema.pxd +35 -0
  131. lxml/includes/xpath.pxd +136 -0
  132. lxml/includes/xslt.pxd +190 -0
  133. lxml/isoschematron/__init__.py +348 -0
  134. lxml/isoschematron/resources/rng/iso-schematron.rng +709 -0
  135. lxml/isoschematron/resources/xsl/RNG2Schtrn.xsl +75 -0
  136. lxml/isoschematron/resources/xsl/XSD2Schtrn.xsl +77 -0
  137. lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_abstract_expand.xsl +313 -0
  138. lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_dsdl_include.xsl +1160 -0
  139. lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_message.xsl +55 -0
  140. lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_skeleton_for_xslt1.xsl +1796 -0
  141. lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_svrl_for_xslt1.xsl +588 -0
  142. lxml/isoschematron/resources/xsl/iso-schematron-xslt1/readme.txt +84 -0
  143. lxml/iterparse.pxi +438 -0
  144. lxml/lxml.etree.h +248 -0
  145. lxml/lxml.etree_api.h +195 -0
  146. lxml/nsclasses.pxi +281 -0
  147. lxml/objectify.cp310-win32.pyd +0 -0
  148. lxml/objectify.pyx +2145 -0
  149. lxml/objectpath.pxi +332 -0
  150. lxml/parser.pxi +2000 -0
  151. lxml/parsertarget.pxi +180 -0
  152. lxml/proxy.pxi +619 -0
  153. lxml/public-api.pxi +178 -0
  154. lxml/pyclasslookup.py +3 -0
  155. lxml/readonlytree.pxi +565 -0
  156. lxml/relaxng.pxi +165 -0
  157. lxml/sax.cp310-win32.pyd +0 -0
  158. lxml/sax.py +275 -0
  159. lxml/saxparser.pxi +875 -0
  160. lxml/schematron.pxi +168 -0
  161. lxml/serializer.pxi +1781 -0
  162. lxml/usedoctest.py +13 -0
  163. lxml/xinclude.pxi +67 -0
  164. lxml/xmlerror.pxi +1654 -0
  165. lxml/xmlid.pxi +179 -0
  166. lxml/xmlschema.pxi +215 -0
  167. lxml/xpath.pxi +487 -0
  168. lxml/xslt.pxi +950 -0
  169. lxml/xsltext.pxi +242 -0
  170. lxml-5.3.2.dist-info/METADATA +100 -0
  171. lxml-5.3.2.dist-info/RECORD +175 -0
  172. lxml-5.3.2.dist-info/WHEEL +5 -0
  173. lxml-5.3.2.dist-info/licenses/LICENSE.txt +29 -0
  174. lxml-5.3.2.dist-info/licenses/LICENSES.txt +29 -0
  175. lxml-5.3.2.dist-info/top_level.txt +1 -0
lxml/etree.pyx ADDED
@@ -0,0 +1,3732 @@
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
+ "Truth-testing of elements was a source of confusion and will always "
1218
+ "return True in future versions. "
1219
+ "Use specific 'len(elem)' or 'elem is not None' test instead.",
1220
+ FutureWarning
1221
+ )
1222
+ # emulate old behaviour
1223
+ _assertValidNode(self)
1224
+ return _hasChild(self._c_node)
1225
+
1226
+ def __contains__(self, element):
1227
+ "__contains__(self, element)"
1228
+ cdef xmlNode* c_node
1229
+ _assertValidNode(self)
1230
+ if not isinstance(element, _Element):
1231
+ return 0
1232
+ c_node = (<_Element>element)._c_node
1233
+ return c_node is not NULL and c_node.parent is self._c_node
1234
+
1235
+ def __iter__(self):
1236
+ "__iter__(self)"
1237
+ return ElementChildIterator(self)
1238
+
1239
+ def __reversed__(self):
1240
+ "__reversed__(self)"
1241
+ return ElementChildIterator(self, reversed=True)
1242
+
1243
+ def index(self, child: _Element, start: int = None, stop: int = None):
1244
+ """index(self, child, start=None, stop=None)
1245
+
1246
+ Find the position of the child within the parent.
1247
+
1248
+ This method is not part of the original ElementTree API.
1249
+ """
1250
+ cdef Py_ssize_t k, l
1251
+ cdef Py_ssize_t c_start, c_stop
1252
+ cdef xmlNode* c_child
1253
+ cdef xmlNode* c_start_node
1254
+ _assertValidNode(self)
1255
+ _assertValidNode(child)
1256
+ c_child = child._c_node
1257
+ if c_child.parent is not self._c_node:
1258
+ raise ValueError, "Element is not a child of this node."
1259
+
1260
+ # handle the unbounded search straight away (normal case)
1261
+ if stop is None and (start is None or start == 0):
1262
+ k = 0
1263
+ c_child = c_child.prev
1264
+ while c_child is not NULL:
1265
+ if _isElement(c_child):
1266
+ k += 1
1267
+ c_child = c_child.prev
1268
+ return k
1269
+
1270
+ # check indices
1271
+ if start is None:
1272
+ c_start = 0
1273
+ else:
1274
+ c_start = start
1275
+ if stop is None:
1276
+ c_stop = 0
1277
+ else:
1278
+ c_stop = stop
1279
+ if c_stop == 0 or \
1280
+ c_start >= c_stop and (c_stop > 0 or c_start < 0):
1281
+ raise ValueError, "list.index(x): x not in slice"
1282
+
1283
+ # for negative slice indices, check slice before searching index
1284
+ if c_start < 0 or c_stop < 0:
1285
+ # start from right, at most up to leftmost(c_start, c_stop)
1286
+ if c_start < c_stop:
1287
+ k = -c_start
1288
+ else:
1289
+ k = -c_stop
1290
+ c_start_node = self._c_node.last
1291
+ l = 1
1292
+ while c_start_node != c_child and l < k:
1293
+ if _isElement(c_start_node):
1294
+ l += 1
1295
+ c_start_node = c_start_node.prev
1296
+ if c_start_node == c_child:
1297
+ # found! before slice end?
1298
+ if c_stop < 0 and l <= -c_stop:
1299
+ raise ValueError, "list.index(x): x not in slice"
1300
+ elif c_start < 0:
1301
+ raise ValueError, "list.index(x): x not in slice"
1302
+
1303
+ # now determine the index backwards from child
1304
+ c_child = c_child.prev
1305
+ k = 0
1306
+ if c_stop > 0:
1307
+ # we can optimize: stop after c_stop elements if not found
1308
+ while c_child != NULL and k < c_stop:
1309
+ if _isElement(c_child):
1310
+ k += 1
1311
+ c_child = c_child.prev
1312
+ if k < c_stop:
1313
+ return k
1314
+ else:
1315
+ # traverse all
1316
+ while c_child != NULL:
1317
+ if _isElement(c_child):
1318
+ k = k + 1
1319
+ c_child = c_child.prev
1320
+ if c_start > 0:
1321
+ if k >= c_start:
1322
+ return k
1323
+ else:
1324
+ return k
1325
+ if c_start != 0 or c_stop != 0:
1326
+ raise ValueError, "list.index(x): x not in slice"
1327
+ else:
1328
+ raise ValueError, "list.index(x): x not in list"
1329
+
1330
+ def get(self, key, default=None):
1331
+ """get(self, key, default=None)
1332
+
1333
+ Gets an element attribute.
1334
+ """
1335
+ _assertValidNode(self)
1336
+ return _getAttributeValue(self, key, default)
1337
+
1338
+ def keys(self):
1339
+ """keys(self)
1340
+
1341
+ Gets a list of attribute names. The names are returned in an
1342
+ arbitrary order (just like for an ordinary Python dictionary).
1343
+ """
1344
+ _assertValidNode(self)
1345
+ return _collectAttributes(self._c_node, 1)
1346
+
1347
+ def values(self):
1348
+ """values(self)
1349
+
1350
+ Gets element attribute values as a sequence of strings. The
1351
+ attributes are returned in an arbitrary order.
1352
+ """
1353
+ _assertValidNode(self)
1354
+ return _collectAttributes(self._c_node, 2)
1355
+
1356
+ def items(self):
1357
+ """items(self)
1358
+
1359
+ Gets element attributes, as a sequence. The attributes are returned in
1360
+ an arbitrary order.
1361
+ """
1362
+ _assertValidNode(self)
1363
+ return _collectAttributes(self._c_node, 3)
1364
+
1365
+ def getchildren(self):
1366
+ """getchildren(self)
1367
+
1368
+ Returns all direct children. The elements are returned in document
1369
+ order.
1370
+
1371
+ :deprecated: Note that this method has been deprecated as of
1372
+ ElementTree 1.3 and lxml 2.0. New code should use
1373
+ ``list(element)`` or simply iterate over elements.
1374
+ """
1375
+ _assertValidNode(self)
1376
+ return _collectChildren(self)
1377
+
1378
+ def getparent(self):
1379
+ """getparent(self)
1380
+
1381
+ Returns the parent of this element or None for the root element.
1382
+ """
1383
+ cdef xmlNode* c_node
1384
+ #_assertValidNode(self) # not needed
1385
+ c_node = _parentElement(self._c_node)
1386
+ if c_node is NULL:
1387
+ return None
1388
+ return _elementFactory(self._doc, c_node)
1389
+
1390
+ def getnext(self):
1391
+ """getnext(self)
1392
+
1393
+ Returns the following sibling of this element or None.
1394
+ """
1395
+ cdef xmlNode* c_node
1396
+ #_assertValidNode(self) # not needed
1397
+ c_node = _nextElement(self._c_node)
1398
+ if c_node is NULL:
1399
+ return None
1400
+ return _elementFactory(self._doc, c_node)
1401
+
1402
+ def getprevious(self):
1403
+ """getprevious(self)
1404
+
1405
+ Returns the preceding sibling of this element or None.
1406
+ """
1407
+ cdef xmlNode* c_node
1408
+ #_assertValidNode(self) # not needed
1409
+ c_node = _previousElement(self._c_node)
1410
+ if c_node is NULL:
1411
+ return None
1412
+ return _elementFactory(self._doc, c_node)
1413
+
1414
+ def itersiblings(self, tag=None, *tags, preceding=False):
1415
+ """itersiblings(self, tag=None, *tags, preceding=False)
1416
+
1417
+ Iterate over the following or preceding siblings of this element.
1418
+
1419
+ The direction is determined by the 'preceding' keyword which
1420
+ defaults to False, i.e. forward iteration over the following
1421
+ siblings. When True, the iterator yields the preceding
1422
+ siblings in reverse document order, i.e. starting right before
1423
+ the current element and going backwards.
1424
+
1425
+ Can be restricted to find only elements with specific tags,
1426
+ see `iter`.
1427
+ """
1428
+ if preceding:
1429
+ if self._c_node and not self._c_node.prev:
1430
+ return ITER_EMPTY
1431
+ elif self._c_node and not self._c_node.next:
1432
+ return ITER_EMPTY
1433
+ if tag is not None:
1434
+ tags += (tag,)
1435
+ return SiblingsIterator(self, tags, preceding=preceding)
1436
+
1437
+ def iterancestors(self, tag=None, *tags):
1438
+ """iterancestors(self, tag=None, *tags)
1439
+
1440
+ Iterate over the ancestors of this element (from parent to parent).
1441
+
1442
+ Can be restricted to find only elements with specific tags,
1443
+ see `iter`.
1444
+ """
1445
+ if self._c_node and not self._c_node.parent:
1446
+ return ITER_EMPTY
1447
+ if tag is not None:
1448
+ tags += (tag,)
1449
+ return AncestorsIterator(self, tags)
1450
+
1451
+ def iterdescendants(self, tag=None, *tags):
1452
+ """iterdescendants(self, tag=None, *tags)
1453
+
1454
+ Iterate over the descendants of this element in document order.
1455
+
1456
+ As opposed to ``el.iter()``, this iterator does not yield the element
1457
+ itself. The returned elements can be restricted to find only elements
1458
+ with specific tags, see `iter`.
1459
+ """
1460
+ if self._c_node and not self._c_node.children:
1461
+ return ITER_EMPTY
1462
+ if tag is not None:
1463
+ tags += (tag,)
1464
+ return ElementDepthFirstIterator(self, tags, inclusive=False)
1465
+
1466
+ def iterchildren(self, tag=None, *tags, reversed=False):
1467
+ """iterchildren(self, tag=None, *tags, reversed=False)
1468
+
1469
+ Iterate over the children of this element.
1470
+
1471
+ As opposed to using normal iteration on this element, the returned
1472
+ elements can be reversed with the 'reversed' keyword and restricted
1473
+ to find only elements with specific tags, see `iter`.
1474
+ """
1475
+ if self._c_node and not self._c_node.children:
1476
+ return ITER_EMPTY
1477
+ if tag is not None:
1478
+ tags += (tag,)
1479
+ return ElementChildIterator(self, tags, reversed=reversed)
1480
+
1481
+ def getroottree(self):
1482
+ """getroottree(self)
1483
+
1484
+ Return an ElementTree for the root node of the document that
1485
+ contains this element.
1486
+
1487
+ This is the same as following element.getparent() up the tree until it
1488
+ returns None (for the root element) and then build an ElementTree for
1489
+ the last parent that was returned."""
1490
+ _assertValidDoc(self._doc)
1491
+ return _elementTreeFactory(self._doc, None)
1492
+
1493
+ def getiterator(self, tag=None, *tags):
1494
+ """getiterator(self, tag=None, *tags)
1495
+
1496
+ Returns a sequence or iterator of all elements in the subtree in
1497
+ document order (depth first pre-order), starting with this
1498
+ element.
1499
+
1500
+ Can be restricted to find only elements with specific tags,
1501
+ see `iter`.
1502
+
1503
+ :deprecated: Note that this method is deprecated as of
1504
+ ElementTree 1.3 and lxml 2.0. It returns an iterator in
1505
+ lxml, which diverges from the original ElementTree
1506
+ behaviour. If you want an efficient iterator, use the
1507
+ ``element.iter()`` method instead. You should only use this
1508
+ method in new code if you require backwards compatibility
1509
+ with older versions of lxml or ElementTree.
1510
+ """
1511
+ if tag is not None:
1512
+ tags += (tag,)
1513
+ return ElementDepthFirstIterator(self, tags)
1514
+
1515
+ def iter(self, tag=None, *tags):
1516
+ """iter(self, tag=None, *tags)
1517
+
1518
+ Iterate over all elements in the subtree in document order (depth
1519
+ first pre-order), starting with this element.
1520
+
1521
+ Can be restricted to find only elements with specific tags:
1522
+ pass ``"{ns}localname"`` as tag. Either or both of ``ns`` and
1523
+ ``localname`` can be ``*`` for a wildcard; ``ns`` can be empty
1524
+ for no namespace. ``"localname"`` is equivalent to ``"{}localname"``
1525
+ (i.e. no namespace) but ``"*"`` is ``"{*}*"`` (any or no namespace),
1526
+ not ``"{}*"``.
1527
+
1528
+ You can also pass the Element, Comment, ProcessingInstruction and
1529
+ Entity factory functions to look only for the specific element type.
1530
+
1531
+ Passing multiple tags (or a sequence of tags) instead of a single tag
1532
+ will let the iterator return all elements matching any of these tags,
1533
+ in document order.
1534
+ """
1535
+ if tag is not None:
1536
+ tags += (tag,)
1537
+ return ElementDepthFirstIterator(self, tags)
1538
+
1539
+ def itertext(self, tag=None, *tags, with_tail=True):
1540
+ """itertext(self, tag=None, *tags, with_tail=True)
1541
+
1542
+ Iterates over the text content of a subtree.
1543
+
1544
+ You can pass tag names to restrict text content to specific elements,
1545
+ see `iter`.
1546
+
1547
+ You can set the ``with_tail`` keyword argument to ``False`` to skip
1548
+ over tail text.
1549
+ """
1550
+ if tag is not None:
1551
+ tags += (tag,)
1552
+ return ElementTextIterator(self, tags, with_tail=with_tail)
1553
+
1554
+ def makeelement(self, _tag, attrib=None, nsmap=None, **_extra):
1555
+ """makeelement(self, _tag, attrib=None, nsmap=None, **_extra)
1556
+
1557
+ Creates a new element associated with the same document.
1558
+ """
1559
+ _assertValidDoc(self._doc)
1560
+ return _makeElement(_tag, NULL, self._doc, None, None, None,
1561
+ attrib, nsmap, _extra)
1562
+
1563
+ def find(self, path, namespaces=None):
1564
+ """find(self, path, namespaces=None)
1565
+
1566
+ Finds the first matching subelement, by tag name or path.
1567
+
1568
+ The optional ``namespaces`` argument accepts a
1569
+ prefix-to-namespace mapping that allows the usage of XPath
1570
+ prefixes in the path expression.
1571
+ """
1572
+ if isinstance(path, QName):
1573
+ path = (<QName>path).text
1574
+ return _elementpath.find(self, path, namespaces, with_prefixes=not _isHtmlDocument(self))
1575
+
1576
+ def findtext(self, path, default=None, namespaces=None):
1577
+ """findtext(self, path, default=None, namespaces=None)
1578
+
1579
+ Finds text for the first matching subelement, by tag name or path.
1580
+
1581
+ The optional ``namespaces`` argument accepts a
1582
+ prefix-to-namespace mapping that allows the usage of XPath
1583
+ prefixes in the path expression.
1584
+ """
1585
+ if isinstance(path, QName):
1586
+ path = (<QName>path).text
1587
+ return _elementpath.findtext(self, path, default, namespaces, with_prefixes=not _isHtmlDocument(self))
1588
+
1589
+ def findall(self, path, namespaces=None):
1590
+ """findall(self, path, namespaces=None)
1591
+
1592
+ Finds all matching subelements, by tag name or path.
1593
+
1594
+ The optional ``namespaces`` argument accepts a
1595
+ prefix-to-namespace mapping that allows the usage of XPath
1596
+ prefixes in the path expression.
1597
+ """
1598
+ if isinstance(path, QName):
1599
+ path = (<QName>path).text
1600
+ return _elementpath.findall(self, path, namespaces, with_prefixes=not _isHtmlDocument(self))
1601
+
1602
+ def iterfind(self, path, namespaces=None):
1603
+ """iterfind(self, path, namespaces=None)
1604
+
1605
+ Iterates over all matching subelements, by tag name or path.
1606
+
1607
+ The optional ``namespaces`` argument accepts a
1608
+ prefix-to-namespace mapping that allows the usage of XPath
1609
+ prefixes in the path expression.
1610
+ """
1611
+ if isinstance(path, QName):
1612
+ path = (<QName>path).text
1613
+ return _elementpath.iterfind(self, path, namespaces, with_prefixes=not _isHtmlDocument(self))
1614
+
1615
+ def xpath(self, _path, *, namespaces=None, extensions=None,
1616
+ smart_strings=True, **_variables):
1617
+ """xpath(self, _path, namespaces=None, extensions=None, smart_strings=True, **_variables)
1618
+
1619
+ Evaluate an xpath expression using the element as context node.
1620
+ """
1621
+ evaluator = XPathElementEvaluator(self, namespaces=namespaces,
1622
+ extensions=extensions,
1623
+ smart_strings=smart_strings)
1624
+ return evaluator(_path, **_variables)
1625
+
1626
+ def cssselect(self, expr, *, translator='xml'):
1627
+ """
1628
+ Run the CSS expression on this element and its children,
1629
+ returning a list of the results.
1630
+
1631
+ Equivalent to lxml.cssselect.CSSSelect(expr)(self) -- note
1632
+ that pre-compiling the expression can provide a substantial
1633
+ speedup.
1634
+ """
1635
+ # Do the import here to make the dependency optional.
1636
+ from lxml.cssselect import CSSSelector
1637
+ return CSSSelector(expr, translator=translator)(self)
1638
+
1639
+
1640
+ cdef extern from "includes/etree_defs.h":
1641
+ # macro call to 't->tp_new()' for fast instantiation
1642
+ cdef object NEW_ELEMENT "PY_NEW" (object t)
1643
+
1644
+
1645
+ @cython.linetrace(False)
1646
+ cdef _Element _elementFactory(_Document doc, xmlNode* c_node):
1647
+ cdef _Element result
1648
+ result = getProxy(c_node)
1649
+ if result is not None:
1650
+ return result
1651
+ if c_node is NULL:
1652
+ return None
1653
+
1654
+ element_class = LOOKUP_ELEMENT_CLASS(
1655
+ ELEMENT_CLASS_LOOKUP_STATE, doc, c_node)
1656
+ if hasProxy(c_node):
1657
+ # prevent re-entry race condition - we just called into Python
1658
+ return getProxy(c_node)
1659
+ result = NEW_ELEMENT(element_class)
1660
+ if hasProxy(c_node):
1661
+ # prevent re-entry race condition - we just called into Python
1662
+ result._c_node = NULL
1663
+ return getProxy(c_node)
1664
+
1665
+ _registerProxy(result, doc, c_node)
1666
+ if element_class is not _Element:
1667
+ result._init()
1668
+ return result
1669
+
1670
+
1671
+ @cython.internal
1672
+ cdef class __ContentOnlyElement(_Element):
1673
+ cdef int _raiseImmutable(self) except -1:
1674
+ raise TypeError, "this element does not have children or attributes"
1675
+
1676
+ def set(self, key, value):
1677
+ "set(self, key, value)"
1678
+ self._raiseImmutable()
1679
+
1680
+ def append(self, value):
1681
+ "append(self, value)"
1682
+ self._raiseImmutable()
1683
+
1684
+ def insert(self, index, value):
1685
+ "insert(self, index, value)"
1686
+ self._raiseImmutable()
1687
+
1688
+ def __setitem__(self, index, value):
1689
+ "__setitem__(self, index, value)"
1690
+ self._raiseImmutable()
1691
+
1692
+ @property
1693
+ def attrib(self):
1694
+ return IMMUTABLE_EMPTY_MAPPING
1695
+
1696
+ property text:
1697
+ def __get__(self):
1698
+ _assertValidNode(self)
1699
+ return funicodeOrEmpty(self._c_node.content)
1700
+
1701
+ def __set__(self, value):
1702
+ cdef tree.xmlDict* c_dict
1703
+ _assertValidNode(self)
1704
+ if value is None:
1705
+ c_text = <const_xmlChar*>NULL
1706
+ else:
1707
+ value = _utf8(value)
1708
+ c_text = _xcstr(value)
1709
+ tree.xmlNodeSetContent(self._c_node, c_text)
1710
+
1711
+ # ACCESSORS
1712
+ def __getitem__(self, x):
1713
+ "__getitem__(self, x)"
1714
+ if isinstance(x, slice):
1715
+ return []
1716
+ else:
1717
+ raise IndexError, "list index out of range"
1718
+
1719
+ def __len__(self):
1720
+ "__len__(self)"
1721
+ return 0
1722
+
1723
+ def get(self, key, default=None):
1724
+ "get(self, key, default=None)"
1725
+ return None
1726
+
1727
+ def keys(self):
1728
+ "keys(self)"
1729
+ return []
1730
+
1731
+ def items(self):
1732
+ "items(self)"
1733
+ return []
1734
+
1735
+ def values(self):
1736
+ "values(self)"
1737
+ return []
1738
+
1739
+ cdef class _Comment(__ContentOnlyElement):
1740
+ @property
1741
+ def tag(self):
1742
+ return Comment
1743
+
1744
+ def __repr__(self):
1745
+ return "<!--%s-->" % self.text
1746
+
1747
+ cdef class _ProcessingInstruction(__ContentOnlyElement):
1748
+ @property
1749
+ def tag(self):
1750
+ return ProcessingInstruction
1751
+
1752
+ property target:
1753
+ # not in ElementTree
1754
+ def __get__(self):
1755
+ _assertValidNode(self)
1756
+ return funicode(self._c_node.name)
1757
+
1758
+ def __set__(self, value):
1759
+ _assertValidNode(self)
1760
+ value = _utf8(value)
1761
+ c_text = _xcstr(value)
1762
+ tree.xmlNodeSetName(self._c_node, c_text)
1763
+
1764
+ def __repr__(self):
1765
+ text = self.text
1766
+ if text:
1767
+ return "<?%s %s?>" % (self.target, text)
1768
+ else:
1769
+ return "<?%s?>" % self.target
1770
+
1771
+ def get(self, key, default=None):
1772
+ """get(self, key, default=None)
1773
+
1774
+ Try to parse pseudo-attributes from the text content of the
1775
+ processing instruction, search for one with the given key as
1776
+ name and return its associated value.
1777
+
1778
+ Note that this is only a convenience method for the most
1779
+ common case that all text content is structured in
1780
+ attribute-like name-value pairs with properly quoted values.
1781
+ It is not guaranteed to work for all possible text content.
1782
+ """
1783
+ return self.attrib.get(key, default)
1784
+
1785
+ @property
1786
+ def attrib(self):
1787
+ """Returns a dict containing all pseudo-attributes that can be
1788
+ parsed from the text content of this processing instruction.
1789
+ Note that modifying the dict currently has no effect on the
1790
+ XML node, although this is not guaranteed to stay this way.
1791
+ """
1792
+ return { attr : (value1 or value2)
1793
+ for attr, value1, value2 in _FIND_PI_ATTRIBUTES(' ' + self.text) }
1794
+
1795
+ cdef object _FIND_PI_ATTRIBUTES = re.compile(r'\s+(\w+)\s*=\s*(?:\'([^\']*)\'|"([^"]*)")', re.U).findall
1796
+
1797
+ cdef class _Entity(__ContentOnlyElement):
1798
+ @property
1799
+ def tag(self):
1800
+ return Entity
1801
+
1802
+ property name:
1803
+ # not in ElementTree
1804
+ def __get__(self):
1805
+ _assertValidNode(self)
1806
+ return funicode(self._c_node.name)
1807
+
1808
+ def __set__(self, value):
1809
+ _assertValidNode(self)
1810
+ value_utf = _utf8(value)
1811
+ if b'&' in value_utf or b';' in value_utf:
1812
+ raise ValueError, f"Invalid entity name '{value}'"
1813
+ tree.xmlNodeSetName(self._c_node, _xcstr(value_utf))
1814
+
1815
+ @property
1816
+ def text(self):
1817
+ # FIXME: should this be None or '&[VALUE];' or the resolved
1818
+ # entity value ?
1819
+ _assertValidNode(self)
1820
+ return f'&{funicode(self._c_node.name)};'
1821
+
1822
+ def __repr__(self):
1823
+ return "&%s;" % self.name
1824
+
1825
+
1826
+ cdef class QName:
1827
+ """QName(text_or_uri_or_element, tag=None)
1828
+
1829
+ QName wrapper for qualified XML names.
1830
+
1831
+ Pass a tag name by itself or a namespace URI and a tag name to
1832
+ create a qualified name. Alternatively, pass an Element to
1833
+ extract its tag name. ``None`` as first argument is ignored in
1834
+ order to allow for generic 2-argument usage.
1835
+
1836
+ The ``text`` property holds the qualified name in
1837
+ ``{namespace}tagname`` notation. The ``namespace`` and
1838
+ ``localname`` properties hold the respective parts of the tag
1839
+ name.
1840
+
1841
+ You can pass QName objects wherever a tag name is expected. Also,
1842
+ setting Element text from a QName will resolve the namespace prefix
1843
+ on assignment and set a qualified text value. This is helpful in XML
1844
+ languages like SOAP or XML-Schema that use prefixed tag names in
1845
+ their text content.
1846
+ """
1847
+ cdef readonly unicode text
1848
+ cdef readonly unicode localname
1849
+ cdef readonly unicode namespace
1850
+ def __init__(self, text_or_uri_or_element, tag=None):
1851
+ if text_or_uri_or_element is None:
1852
+ # Allow None as no namespace.
1853
+ text_or_uri_or_element, tag = tag, None
1854
+ if not _isString(text_or_uri_or_element):
1855
+ if isinstance(text_or_uri_or_element, _Element):
1856
+ text_or_uri_or_element = (<_Element>text_or_uri_or_element).tag
1857
+ if not _isString(text_or_uri_or_element):
1858
+ raise ValueError, f"Invalid input tag of type {type(text_or_uri_or_element)!r}"
1859
+ elif isinstance(text_or_uri_or_element, QName):
1860
+ text_or_uri_or_element = (<QName>text_or_uri_or_element).text
1861
+ elif text_or_uri_or_element is not None:
1862
+ text_or_uri_or_element = unicode(text_or_uri_or_element)
1863
+ else:
1864
+ raise ValueError, f"Invalid input tag of type {type(text_or_uri_or_element)!r}"
1865
+
1866
+ ns_utf, tag_utf = _getNsTag(text_or_uri_or_element)
1867
+ if tag is not None:
1868
+ # either ('ns', 'tag') or ('{ns}oldtag', 'newtag')
1869
+ if ns_utf is None:
1870
+ ns_utf = tag_utf # case 1: namespace ended up as tag name
1871
+ tag_utf = _utf8(tag)
1872
+ _tagValidOrRaise(tag_utf)
1873
+ self.localname = (<bytes>tag_utf).decode('utf8')
1874
+ if ns_utf is None:
1875
+ self.namespace = None
1876
+ self.text = self.localname
1877
+ else:
1878
+ self.namespace = (<bytes>ns_utf).decode('utf8')
1879
+ self.text = "{%s}%s" % (self.namespace, self.localname)
1880
+ def __str__(self):
1881
+ return self.text
1882
+ def __hash__(self):
1883
+ return hash(self.text)
1884
+ def __richcmp__(self, other, int op):
1885
+ try:
1886
+ if type(other) is QName:
1887
+ other = (<QName>other).text
1888
+ elif not isinstance(other, unicode):
1889
+ other = unicode(other)
1890
+ except (ValueError, UnicodeDecodeError):
1891
+ return NotImplemented
1892
+ return python.PyObject_RichCompare(self.text, other, op)
1893
+
1894
+
1895
+ cdef public class _ElementTree [ type LxmlElementTreeType,
1896
+ object LxmlElementTree ]:
1897
+ cdef _Document _doc
1898
+ cdef _Element _context_node
1899
+
1900
+ # Note that _doc is only used to store the original document if we do not
1901
+ # have a _context_node. All methods should prefer self._context_node._doc
1902
+ # to honour tree restructuring. _doc can happily be None!
1903
+
1904
+ @cython.final
1905
+ cdef int _assertHasRoot(self) except -1:
1906
+ """We have to take care here: the document may not have a root node!
1907
+ This can happen if ElementTree() is called without any argument and
1908
+ the caller 'forgets' to call parse() afterwards, so this is a bug in
1909
+ the caller program.
1910
+ """
1911
+ assert self._context_node is not None, \
1912
+ "ElementTree not initialized, missing root"
1913
+ return 0
1914
+
1915
+ def parse(self, source, _BaseParser parser=None, *, base_url=None):
1916
+ """parse(self, source, parser=None, base_url=None)
1917
+
1918
+ Updates self with the content of source and returns its root.
1919
+ """
1920
+ cdef _Document doc = None
1921
+ try:
1922
+ doc = _parseDocument(source, parser, base_url)
1923
+ except _TargetParserResult as result_container:
1924
+ # raises a TypeError if we don't get an _Element
1925
+ self._context_node = result_container.result
1926
+ else:
1927
+ self._context_node = doc.getroot()
1928
+ self._doc = None if self._context_node is not None else doc
1929
+ return self._context_node
1930
+
1931
+ def _setroot(self, _Element root not None):
1932
+ """_setroot(self, root)
1933
+
1934
+ Relocate the ElementTree to a new root node.
1935
+ """
1936
+ _assertValidNode(root)
1937
+ if root._c_node.type != tree.XML_ELEMENT_NODE:
1938
+ raise TypeError, "Only elements can be the root of an ElementTree"
1939
+ self._context_node = root
1940
+ self._doc = None
1941
+
1942
+ def getroot(self):
1943
+ """getroot(self)
1944
+
1945
+ Gets the root element for this tree.
1946
+ """
1947
+ return self._context_node
1948
+
1949
+ def __copy__(self):
1950
+ return _elementTreeFactory(self._doc, self._context_node)
1951
+
1952
+ def __deepcopy__(self, memo):
1953
+ cdef _Element root
1954
+ cdef _Document doc
1955
+ cdef xmlDoc* c_doc
1956
+ if self._context_node is not None:
1957
+ root = self._context_node.__copy__()
1958
+ assert root is not None
1959
+ _assertValidNode(root)
1960
+ _copyNonElementSiblings(self._context_node._c_node, root._c_node)
1961
+ return _elementTreeFactory(None, root)
1962
+ elif self._doc is not None:
1963
+ _assertValidDoc(self._doc)
1964
+ c_doc = tree.xmlCopyDoc(self._doc._c_doc, 1)
1965
+ if c_doc is NULL:
1966
+ raise MemoryError()
1967
+ doc = _documentFactory(c_doc, self._doc._parser)
1968
+ return _elementTreeFactory(doc, None)
1969
+ else:
1970
+ # so what ...
1971
+ return self
1972
+
1973
+ # not in ElementTree
1974
+ @property
1975
+ def docinfo(self) -> DocInfo:
1976
+ """Information about the document provided by parser and DTD."""
1977
+ self._assertHasRoot()
1978
+ return DocInfo(self._context_node._doc)
1979
+
1980
+ # not in ElementTree, read-only
1981
+ @property
1982
+ def parser(self):
1983
+ """The parser that was used to parse the document in this ElementTree.
1984
+ """
1985
+ if self._context_node is not None and \
1986
+ self._context_node._doc is not None:
1987
+ return self._context_node._doc._parser
1988
+ if self._doc is not None:
1989
+ return self._doc._parser
1990
+ return None
1991
+
1992
+ def write(self, file, *, encoding=None, method="xml",
1993
+ bint pretty_print=False, xml_declaration=None, bint with_tail=True,
1994
+ standalone=None, doctype=None, compression=0,
1995
+ bint exclusive=False, inclusive_ns_prefixes=None,
1996
+ bint with_comments=True, bint strip_text=False,
1997
+ docstring=None):
1998
+ """write(self, file, encoding=None, method="xml",
1999
+ pretty_print=False, xml_declaration=None, with_tail=True,
2000
+ standalone=None, doctype=None, compression=0,
2001
+ exclusive=False, inclusive_ns_prefixes=None,
2002
+ with_comments=True, strip_text=False)
2003
+
2004
+ Write the tree to a filename, file or file-like object.
2005
+
2006
+ Defaults to ASCII encoding and writing a declaration as needed.
2007
+
2008
+ The keyword argument 'method' selects the output method:
2009
+ 'xml', 'html', 'text', 'c14n' or 'c14n2'. Default is 'xml'.
2010
+
2011
+ With ``method="c14n"`` (C14N version 1), the options ``exclusive``,
2012
+ ``with_comments`` and ``inclusive_ns_prefixes`` request exclusive
2013
+ C14N, include comments, and list the inclusive prefixes respectively.
2014
+
2015
+ With ``method="c14n2"`` (C14N version 2), the ``with_comments`` and
2016
+ ``strip_text`` options control the output of comments and text space
2017
+ according to C14N 2.0.
2018
+
2019
+ Passing a boolean value to the ``standalone`` option will
2020
+ output an XML declaration with the corresponding
2021
+ ``standalone`` flag.
2022
+
2023
+ The ``doctype`` option allows passing in a plain string that will
2024
+ be serialised before the XML tree. Note that passing in non
2025
+ well-formed content here will make the XML output non well-formed.
2026
+ Also, an existing doctype in the document tree will not be removed
2027
+ when serialising an ElementTree instance.
2028
+
2029
+ The ``compression`` option enables GZip compression level 1-9.
2030
+
2031
+ The ``inclusive_ns_prefixes`` should be a list of namespace strings
2032
+ (i.e. ['xs', 'xsi']) that will be promoted to the top-level element
2033
+ during exclusive C14N serialisation. This parameter is ignored if
2034
+ exclusive mode=False.
2035
+
2036
+ If exclusive=True and no list is provided, a namespace will only be
2037
+ rendered if it is used by the immediate parent or one of its attributes
2038
+ and its prefix and values have not already been rendered by an ancestor
2039
+ of the namespace node's parent element.
2040
+ """
2041
+ cdef bint write_declaration
2042
+ cdef int is_standalone
2043
+
2044
+ self._assertHasRoot()
2045
+ _assertValidNode(self._context_node)
2046
+ if compression is None or compression < 0:
2047
+ compression = 0
2048
+
2049
+ # C14N serialisation
2050
+ if method in ('c14n', 'c14n2'):
2051
+ if encoding is not None:
2052
+ raise ValueError("Cannot specify encoding with C14N")
2053
+ if xml_declaration:
2054
+ raise ValueError("Cannot enable XML declaration in C14N")
2055
+
2056
+ if method == 'c14n':
2057
+ _tofilelikeC14N(file, self._context_node, exclusive, with_comments,
2058
+ compression, inclusive_ns_prefixes)
2059
+ else: # c14n2
2060
+ with _open_utf8_file(file, compression=compression) as f:
2061
+ target = C14NWriterTarget(
2062
+ f.write, with_comments=with_comments, strip_text=strip_text)
2063
+ _tree_to_target(self, target)
2064
+ return
2065
+
2066
+ if not with_comments:
2067
+ raise ValueError("Can only discard comments in C14N serialisation")
2068
+ # suppress decl. in default case (purely for ElementTree compatibility)
2069
+ if xml_declaration is not None:
2070
+ write_declaration = xml_declaration
2071
+ if encoding is None:
2072
+ encoding = 'ASCII'
2073
+ else:
2074
+ encoding = encoding.upper()
2075
+ elif encoding is None:
2076
+ encoding = 'ASCII'
2077
+ write_declaration = 0
2078
+ else:
2079
+ encoding = encoding.upper()
2080
+ write_declaration = encoding not in (
2081
+ 'US-ASCII', 'ASCII', 'UTF8', 'UTF-8')
2082
+ if standalone is None:
2083
+ is_standalone = -1
2084
+ elif standalone:
2085
+ write_declaration = 1
2086
+ is_standalone = 1
2087
+ else:
2088
+ write_declaration = 1
2089
+ is_standalone = 0
2090
+
2091
+ if docstring is not None and doctype is None:
2092
+ import warnings
2093
+ warnings.warn(
2094
+ "The 'docstring' option is deprecated. Use 'doctype' instead.",
2095
+ DeprecationWarning)
2096
+ doctype = docstring
2097
+
2098
+ _tofilelike(file, self._context_node, encoding, doctype, method,
2099
+ write_declaration, 1, pretty_print, with_tail,
2100
+ is_standalone, compression)
2101
+
2102
+ def getpath(self, _Element element not None):
2103
+ """getpath(self, element)
2104
+
2105
+ Returns a structural, absolute XPath expression to find the element.
2106
+
2107
+ For namespaced elements, the expression uses prefixes from the
2108
+ document, which therefore need to be provided in order to make any
2109
+ use of the expression in XPath.
2110
+
2111
+ Also see the method getelementpath(self, element), which returns a
2112
+ self-contained ElementPath expression.
2113
+ """
2114
+ cdef _Document doc
2115
+ cdef _Element root
2116
+ cdef xmlDoc* c_doc
2117
+ _assertValidNode(element)
2118
+ if self._context_node is not None:
2119
+ root = self._context_node
2120
+ doc = root._doc
2121
+ elif self._doc is not None:
2122
+ doc = self._doc
2123
+ root = doc.getroot()
2124
+ else:
2125
+ raise ValueError, "Element is not in this tree."
2126
+ _assertValidDoc(doc)
2127
+ _assertValidNode(root)
2128
+ if element._doc is not doc:
2129
+ raise ValueError, "Element is not in this tree."
2130
+
2131
+ c_doc = _fakeRootDoc(doc._c_doc, root._c_node)
2132
+ c_path = tree.xmlGetNodePath(element._c_node)
2133
+ _destroyFakeDoc(doc._c_doc, c_doc)
2134
+ if c_path is NULL:
2135
+ raise MemoryError()
2136
+ path = funicode(c_path)
2137
+ tree.xmlFree(c_path)
2138
+ return path
2139
+
2140
+ def getelementpath(self, _Element element not None):
2141
+ """getelementpath(self, element)
2142
+
2143
+ Returns a structural, absolute ElementPath expression to find the
2144
+ element. This path can be used in the .find() method to look up
2145
+ the element, provided that the elements along the path and their
2146
+ list of immediate children were not modified in between.
2147
+
2148
+ ElementPath has the advantage over an XPath expression (as returned
2149
+ by the .getpath() method) that it does not require additional prefix
2150
+ declarations. It is always self-contained.
2151
+ """
2152
+ cdef _Element root
2153
+ cdef Py_ssize_t count
2154
+ _assertValidNode(element)
2155
+ if element._c_node.type != tree.XML_ELEMENT_NODE:
2156
+ raise ValueError, "input is not an Element"
2157
+ if self._context_node is not None:
2158
+ root = self._context_node
2159
+ elif self._doc is not None:
2160
+ root = self._doc.getroot()
2161
+ else:
2162
+ raise ValueError, "Element is not in this tree"
2163
+ _assertValidNode(root)
2164
+ if element._doc is not root._doc:
2165
+ raise ValueError, "Element is not in this tree"
2166
+
2167
+ path = []
2168
+ c_element = element._c_node
2169
+ while c_element is not root._c_node:
2170
+ c_name = c_element.name
2171
+ c_href = _getNs(c_element)
2172
+ tag = _namespacedNameFromNsName(c_href, c_name)
2173
+ if c_href is NULL:
2174
+ c_href = <const_xmlChar*>b'' # no namespace (NULL is wildcard)
2175
+ # use tag[N] if there are preceding siblings with the same tag
2176
+ count = 0
2177
+ c_node = c_element.prev
2178
+ while c_node is not NULL:
2179
+ if c_node.type == tree.XML_ELEMENT_NODE:
2180
+ if _tagMatches(c_node, c_href, c_name):
2181
+ count += 1
2182
+ c_node = c_node.prev
2183
+ if count:
2184
+ tag = f'{tag}[{count+1}]'
2185
+ else:
2186
+ # use tag[1] if there are following siblings with the same tag
2187
+ c_node = c_element.next
2188
+ while c_node is not NULL:
2189
+ if c_node.type == tree.XML_ELEMENT_NODE:
2190
+ if _tagMatches(c_node, c_href, c_name):
2191
+ tag += '[1]'
2192
+ break
2193
+ c_node = c_node.next
2194
+
2195
+ path.append(tag)
2196
+ c_element = c_element.parent
2197
+ if c_element is NULL or c_element.type != tree.XML_ELEMENT_NODE:
2198
+ raise ValueError, "Element is not in this tree."
2199
+ if not path:
2200
+ return '.'
2201
+ path.reverse()
2202
+ return '/'.join(path)
2203
+
2204
+ def getiterator(self, tag=None, *tags):
2205
+ """getiterator(self, *tags, tag=None)
2206
+
2207
+ Returns a sequence or iterator of all elements in document order
2208
+ (depth first pre-order), starting with the root element.
2209
+
2210
+ Can be restricted to find only elements with specific tags,
2211
+ see `_Element.iter`.
2212
+
2213
+ :deprecated: Note that this method is deprecated as of
2214
+ ElementTree 1.3 and lxml 2.0. It returns an iterator in
2215
+ lxml, which diverges from the original ElementTree
2216
+ behaviour. If you want an efficient iterator, use the
2217
+ ``tree.iter()`` method instead. You should only use this
2218
+ method in new code if you require backwards compatibility
2219
+ with older versions of lxml or ElementTree.
2220
+ """
2221
+ root = self.getroot()
2222
+ if root is None:
2223
+ return ITER_EMPTY
2224
+ if tag is not None:
2225
+ tags += (tag,)
2226
+ return root.getiterator(*tags)
2227
+
2228
+ def iter(self, tag=None, *tags):
2229
+ """iter(self, tag=None, *tags)
2230
+
2231
+ Creates an iterator for the root element. The iterator loops over
2232
+ all elements in this tree, in document order. Note that siblings
2233
+ of the root element (comments or processing instructions) are not
2234
+ returned by the iterator.
2235
+
2236
+ Can be restricted to find only elements with specific tags,
2237
+ see `_Element.iter`.
2238
+ """
2239
+ root = self.getroot()
2240
+ if root is None:
2241
+ return ITER_EMPTY
2242
+ if tag is not None:
2243
+ tags += (tag,)
2244
+ return root.iter(*tags)
2245
+
2246
+ def find(self, path, namespaces=None):
2247
+ """find(self, path, namespaces=None)
2248
+
2249
+ Finds the first toplevel element with given tag. Same as
2250
+ ``tree.getroot().find(path)``.
2251
+
2252
+ The optional ``namespaces`` argument accepts a
2253
+ prefix-to-namespace mapping that allows the usage of XPath
2254
+ prefixes in the path expression.
2255
+ """
2256
+ self._assertHasRoot()
2257
+ root = self.getroot()
2258
+ if _isString(path):
2259
+ if path[:1] == "/":
2260
+ path = "." + path
2261
+ from warnings import warn
2262
+ warn(
2263
+ "This search incorrectly ignores the root element, and will be "
2264
+ "fixed in a future version. If you rely on the current "
2265
+ f"behaviour, change it to {path!r}",
2266
+ FutureWarning, stacklevel=1
2267
+ )
2268
+ return root.find(path, namespaces)
2269
+
2270
+ def findtext(self, path, default=None, namespaces=None):
2271
+ """findtext(self, path, default=None, namespaces=None)
2272
+
2273
+ Finds the text for the first element matching the ElementPath
2274
+ expression. Same as getroot().findtext(path)
2275
+
2276
+ The optional ``namespaces`` argument accepts a
2277
+ prefix-to-namespace mapping that allows the usage of XPath
2278
+ prefixes in the path expression.
2279
+ """
2280
+ self._assertHasRoot()
2281
+ root = self.getroot()
2282
+ if _isString(path):
2283
+ if path[:1] == "/":
2284
+ path = "." + path
2285
+ from warnings import warn
2286
+ warn(
2287
+ "This search incorrectly ignores the root element, and will be "
2288
+ "fixed in a future version. If you rely on the current "
2289
+ f"behaviour, change it to {path!r}",
2290
+ FutureWarning, stacklevel=1
2291
+ )
2292
+ return root.findtext(path, default, namespaces)
2293
+
2294
+ def findall(self, path, namespaces=None):
2295
+ """findall(self, path, namespaces=None)
2296
+
2297
+ Finds all elements matching the ElementPath expression. Same as
2298
+ getroot().findall(path).
2299
+
2300
+ The optional ``namespaces`` argument accepts a
2301
+ prefix-to-namespace mapping that allows the usage of XPath
2302
+ prefixes in the path expression.
2303
+ """
2304
+ self._assertHasRoot()
2305
+ root = self.getroot()
2306
+ if _isString(path):
2307
+ if path[:1] == "/":
2308
+ path = "." + path
2309
+ from warnings import warn
2310
+ warn(
2311
+ "This search incorrectly ignores the root element, and will be "
2312
+ "fixed in a future version. If you rely on the current "
2313
+ f"behaviour, change it to {path!r}",
2314
+ FutureWarning, stacklevel=1
2315
+ )
2316
+ return root.findall(path, namespaces)
2317
+
2318
+ def iterfind(self, path, namespaces=None):
2319
+ """iterfind(self, path, namespaces=None)
2320
+
2321
+ Iterates over all elements matching the ElementPath expression.
2322
+ Same as getroot().iterfind(path).
2323
+
2324
+ The optional ``namespaces`` argument accepts a
2325
+ prefix-to-namespace mapping that allows the usage of XPath
2326
+ prefixes in the path expression.
2327
+ """
2328
+ self._assertHasRoot()
2329
+ root = self.getroot()
2330
+ if _isString(path):
2331
+ if path[:1] == "/":
2332
+ path = "." + path
2333
+ from warnings import warn
2334
+ warn(
2335
+ "This search incorrectly ignores the root element, and will be "
2336
+ "fixed in a future version. If you rely on the current "
2337
+ f"behaviour, change it to {path!r}",
2338
+ FutureWarning, stacklevel=1
2339
+ )
2340
+ return root.iterfind(path, namespaces)
2341
+
2342
+ def xpath(self, _path, *, namespaces=None, extensions=None,
2343
+ smart_strings=True, **_variables):
2344
+ """xpath(self, _path, namespaces=None, extensions=None, smart_strings=True, **_variables)
2345
+
2346
+ XPath evaluate in context of document.
2347
+
2348
+ ``namespaces`` is an optional dictionary with prefix to namespace URI
2349
+ mappings, used by XPath. ``extensions`` defines additional extension
2350
+ functions.
2351
+
2352
+ Returns a list (nodeset), or bool, float or string.
2353
+
2354
+ In case of a list result, return Element for element nodes,
2355
+ string for text and attribute values.
2356
+
2357
+ Note: if you are going to apply multiple XPath expressions
2358
+ against the same document, it is more efficient to use
2359
+ XPathEvaluator directly.
2360
+ """
2361
+ self._assertHasRoot()
2362
+ evaluator = XPathDocumentEvaluator(self, namespaces=namespaces,
2363
+ extensions=extensions,
2364
+ smart_strings=smart_strings)
2365
+ return evaluator(_path, **_variables)
2366
+
2367
+ def xslt(self, _xslt, extensions=None, access_control=None, **_kw):
2368
+ """xslt(self, _xslt, extensions=None, access_control=None, **_kw)
2369
+
2370
+ Transform this document using other document.
2371
+
2372
+ xslt is a tree that should be XSLT
2373
+ keyword parameters are XSLT transformation parameters.
2374
+
2375
+ Returns the transformed tree.
2376
+
2377
+ Note: if you are going to apply the same XSLT stylesheet against
2378
+ multiple documents, it is more efficient to use the XSLT
2379
+ class directly.
2380
+ """
2381
+ self._assertHasRoot()
2382
+ style = XSLT(_xslt, extensions=extensions,
2383
+ access_control=access_control)
2384
+ return style(self, **_kw)
2385
+
2386
+ def relaxng(self, relaxng):
2387
+ """relaxng(self, relaxng)
2388
+
2389
+ Validate this document using other document.
2390
+
2391
+ The relaxng argument is a tree that should contain a Relax NG schema.
2392
+
2393
+ Returns True or False, depending on whether validation
2394
+ succeeded.
2395
+
2396
+ Note: if you are going to apply the same Relax NG schema against
2397
+ multiple documents, it is more efficient to use the RelaxNG
2398
+ class directly.
2399
+ """
2400
+ self._assertHasRoot()
2401
+ schema = RelaxNG(relaxng)
2402
+ return schema.validate(self)
2403
+
2404
+ def xmlschema(self, xmlschema):
2405
+ """xmlschema(self, xmlschema)
2406
+
2407
+ Validate this document using other document.
2408
+
2409
+ The xmlschema argument is a tree that should contain an XML Schema.
2410
+
2411
+ Returns True or False, depending on whether validation
2412
+ succeeded.
2413
+
2414
+ Note: If you are going to apply the same XML Schema against
2415
+ multiple documents, it is more efficient to use the XMLSchema
2416
+ class directly.
2417
+ """
2418
+ self._assertHasRoot()
2419
+ schema = XMLSchema(xmlschema)
2420
+ return schema.validate(self)
2421
+
2422
+ def xinclude(self):
2423
+ """xinclude(self)
2424
+
2425
+ Process the XInclude nodes in this document and include the
2426
+ referenced XML fragments.
2427
+
2428
+ There is support for loading files through the file system, HTTP and
2429
+ FTP.
2430
+
2431
+ Note that XInclude does not support custom resolvers in Python space
2432
+ due to restrictions of libxml2 <= 2.6.29.
2433
+ """
2434
+ self._assertHasRoot()
2435
+ XInclude()(self._context_node)
2436
+
2437
+ def write_c14n(self, file, *, bint exclusive=False, bint with_comments=True,
2438
+ compression=0, inclusive_ns_prefixes=None):
2439
+ """write_c14n(self, file, exclusive=False, with_comments=True,
2440
+ compression=0, inclusive_ns_prefixes=None)
2441
+
2442
+ C14N write of document. Always writes UTF-8.
2443
+
2444
+ The ``compression`` option enables GZip compression level 1-9.
2445
+
2446
+ The ``inclusive_ns_prefixes`` should be a list of namespace strings
2447
+ (i.e. ['xs', 'xsi']) that will be promoted to the top-level element
2448
+ during exclusive C14N serialisation. This parameter is ignored if
2449
+ exclusive mode=False.
2450
+
2451
+ If exclusive=True and no list is provided, a namespace will only be
2452
+ rendered if it is used by the immediate parent or one of its attributes
2453
+ and its prefix and values have not already been rendered by an ancestor
2454
+ of the namespace node's parent element.
2455
+
2456
+ NOTE: This method is deprecated as of lxml 4.4 and will be removed in a
2457
+ future release. Use ``.write(f, method="c14n")`` instead.
2458
+ """
2459
+ self._assertHasRoot()
2460
+ _assertValidNode(self._context_node)
2461
+ if compression is None or compression < 0:
2462
+ compression = 0
2463
+
2464
+ _tofilelikeC14N(file, self._context_node, exclusive, with_comments,
2465
+ compression, inclusive_ns_prefixes)
2466
+
2467
+ cdef _ElementTree _elementTreeFactory(_Document doc, _Element context_node):
2468
+ return _newElementTree(doc, context_node, _ElementTree)
2469
+
2470
+ cdef _ElementTree _newElementTree(_Document doc, _Element context_node,
2471
+ object baseclass):
2472
+ cdef _ElementTree result
2473
+ result = baseclass()
2474
+ if context_node is None and doc is not None:
2475
+ context_node = doc.getroot()
2476
+ if context_node is None:
2477
+ _assertValidDoc(doc)
2478
+ result._doc = doc
2479
+ else:
2480
+ _assertValidNode(context_node)
2481
+ result._context_node = context_node
2482
+ return result
2483
+
2484
+
2485
+ @cython.final
2486
+ @cython.freelist(16)
2487
+ cdef class _Attrib:
2488
+ """A dict-like proxy for the ``Element.attrib`` property.
2489
+ """
2490
+ cdef _Element _element
2491
+ def __cinit__(self, _Element element not None):
2492
+ _assertValidNode(element)
2493
+ self._element = element
2494
+
2495
+ # MANIPULATORS
2496
+ def __setitem__(self, key, value):
2497
+ _assertValidNode(self._element)
2498
+ _setAttributeValue(self._element, key, value)
2499
+
2500
+ def __delitem__(self, key):
2501
+ _assertValidNode(self._element)
2502
+ _delAttribute(self._element, key)
2503
+
2504
+ def update(self, sequence_or_dict):
2505
+ _assertValidNode(self._element)
2506
+ if isinstance(sequence_or_dict, (dict, _Attrib)):
2507
+ sequence_or_dict = sequence_or_dict.items()
2508
+ for key, value in sequence_or_dict:
2509
+ _setAttributeValue(self._element, key, value)
2510
+
2511
+ def pop(self, key, *default):
2512
+ if len(default) > 1:
2513
+ raise TypeError, f"pop expected at most 2 arguments, got {len(default)+1}"
2514
+ _assertValidNode(self._element)
2515
+ result = _getAttributeValue(self._element, key, None)
2516
+ if result is None:
2517
+ if not default:
2518
+ raise KeyError, key
2519
+ result = default[0]
2520
+ else:
2521
+ _delAttribute(self._element, key)
2522
+ return result
2523
+
2524
+ def clear(self):
2525
+ _assertValidNode(self._element)
2526
+ c_attrs = self._element._c_node.properties
2527
+ if c_attrs:
2528
+ self._element._c_node.properties = NULL
2529
+ tree.xmlFreePropList(c_attrs)
2530
+
2531
+ # ACCESSORS
2532
+ def __repr__(self):
2533
+ _assertValidNode(self._element)
2534
+ return repr(dict( _collectAttributes(self._element._c_node, 3) ))
2535
+
2536
+ def __copy__(self):
2537
+ _assertValidNode(self._element)
2538
+ return dict(_collectAttributes(self._element._c_node, 3))
2539
+
2540
+ def __deepcopy__(self, memo):
2541
+ _assertValidNode(self._element)
2542
+ return dict(_collectAttributes(self._element._c_node, 3))
2543
+
2544
+ def __getitem__(self, key):
2545
+ _assertValidNode(self._element)
2546
+ result = _getAttributeValue(self._element, key, None)
2547
+ if result is None:
2548
+ raise KeyError, key
2549
+ return result
2550
+
2551
+ def __bool__(self):
2552
+ _assertValidNode(self._element)
2553
+ cdef xmlAttr* c_attr = self._element._c_node.properties
2554
+ while c_attr is not NULL:
2555
+ if c_attr.type == tree.XML_ATTRIBUTE_NODE:
2556
+ return 1
2557
+ c_attr = c_attr.next
2558
+ return 0
2559
+
2560
+ def __len__(self):
2561
+ _assertValidNode(self._element)
2562
+ cdef xmlAttr* c_attr = self._element._c_node.properties
2563
+ cdef Py_ssize_t c = 0
2564
+ while c_attr is not NULL:
2565
+ if c_attr.type == tree.XML_ATTRIBUTE_NODE:
2566
+ c += 1
2567
+ c_attr = c_attr.next
2568
+ return c
2569
+
2570
+ def get(self, key, default=None):
2571
+ _assertValidNode(self._element)
2572
+ return _getAttributeValue(self._element, key, default)
2573
+
2574
+ def keys(self):
2575
+ _assertValidNode(self._element)
2576
+ return _collectAttributes(self._element._c_node, 1)
2577
+
2578
+ def __iter__(self):
2579
+ _assertValidNode(self._element)
2580
+ return iter(_collectAttributes(self._element._c_node, 1))
2581
+
2582
+ def iterkeys(self):
2583
+ _assertValidNode(self._element)
2584
+ return iter(_collectAttributes(self._element._c_node, 1))
2585
+
2586
+ def values(self):
2587
+ _assertValidNode(self._element)
2588
+ return _collectAttributes(self._element._c_node, 2)
2589
+
2590
+ def itervalues(self):
2591
+ _assertValidNode(self._element)
2592
+ return iter(_collectAttributes(self._element._c_node, 2))
2593
+
2594
+ def items(self):
2595
+ _assertValidNode(self._element)
2596
+ return _collectAttributes(self._element._c_node, 3)
2597
+
2598
+ def iteritems(self):
2599
+ _assertValidNode(self._element)
2600
+ return iter(_collectAttributes(self._element._c_node, 3))
2601
+
2602
+ def has_key(self, key):
2603
+ _assertValidNode(self._element)
2604
+ return key in self
2605
+
2606
+ def __contains__(self, key):
2607
+ _assertValidNode(self._element)
2608
+ cdef xmlNode* c_node
2609
+ ns, tag = _getNsTag(key)
2610
+ c_node = self._element._c_node
2611
+ c_href = <const_xmlChar*>NULL if ns is None else _xcstr(ns)
2612
+ return 1 if tree.xmlHasNsProp(c_node, _xcstr(tag), c_href) else 0
2613
+
2614
+ def __richcmp__(self, other, int op):
2615
+ try:
2616
+ one = dict(self.items())
2617
+ if not isinstance(other, dict):
2618
+ other = dict(other)
2619
+ except (TypeError, ValueError):
2620
+ return NotImplemented
2621
+ return python.PyObject_RichCompare(one, other, op)
2622
+
2623
+ MutableMapping.register(_Attrib)
2624
+
2625
+
2626
+ @cython.final
2627
+ @cython.internal
2628
+ cdef class _AttribIterator:
2629
+ """Attribute iterator - for internal use only!
2630
+ """
2631
+ # XML attributes must not be removed while running!
2632
+ cdef _Element _node
2633
+ cdef xmlAttr* _c_attr
2634
+ cdef int _keysvalues # 1 - keys, 2 - values, 3 - items (key, value)
2635
+ def __iter__(self):
2636
+ return self
2637
+
2638
+ def __next__(self):
2639
+ cdef xmlAttr* c_attr
2640
+ if self._node is None:
2641
+ raise StopIteration
2642
+ c_attr = self._c_attr
2643
+ while c_attr is not NULL and c_attr.type != tree.XML_ATTRIBUTE_NODE:
2644
+ c_attr = c_attr.next
2645
+ if c_attr is NULL:
2646
+ self._node = None
2647
+ raise StopIteration
2648
+
2649
+ self._c_attr = c_attr.next
2650
+ if self._keysvalues == 1:
2651
+ return _namespacedName(<xmlNode*>c_attr)
2652
+ elif self._keysvalues == 2:
2653
+ return _attributeValue(self._node._c_node, c_attr)
2654
+ else:
2655
+ return (_namespacedName(<xmlNode*>c_attr),
2656
+ _attributeValue(self._node._c_node, c_attr))
2657
+
2658
+ cdef object _attributeIteratorFactory(_Element element, int keysvalues):
2659
+ cdef _AttribIterator attribs
2660
+ if element._c_node.properties is NULL:
2661
+ return ITER_EMPTY
2662
+ attribs = _AttribIterator()
2663
+ attribs._node = element
2664
+ attribs._c_attr = element._c_node.properties
2665
+ attribs._keysvalues = keysvalues
2666
+ return attribs
2667
+
2668
+
2669
+ cdef public class _ElementTagMatcher [ object LxmlElementTagMatcher,
2670
+ type LxmlElementTagMatcherType ]:
2671
+ """
2672
+ Dead but public. :)
2673
+ """
2674
+ cdef object _pystrings
2675
+ cdef int _node_type
2676
+ cdef char* _href
2677
+ cdef char* _name
2678
+ cdef _initTagMatch(self, tag):
2679
+ self._href = NULL
2680
+ self._name = NULL
2681
+ if tag is None:
2682
+ self._node_type = 0
2683
+ elif tag is Comment:
2684
+ self._node_type = tree.XML_COMMENT_NODE
2685
+ elif tag is ProcessingInstruction:
2686
+ self._node_type = tree.XML_PI_NODE
2687
+ elif tag is Entity:
2688
+ self._node_type = tree.XML_ENTITY_REF_NODE
2689
+ elif tag is Element:
2690
+ self._node_type = tree.XML_ELEMENT_NODE
2691
+ else:
2692
+ self._node_type = tree.XML_ELEMENT_NODE
2693
+ self._pystrings = _getNsTag(tag)
2694
+ if self._pystrings[0] is not None:
2695
+ self._href = _cstr(self._pystrings[0])
2696
+ self._name = _cstr(self._pystrings[1])
2697
+ if self._name[0] == c'*' and self._name[1] == c'\0':
2698
+ self._name = NULL
2699
+
2700
+ cdef public class _ElementIterator(_ElementTagMatcher) [
2701
+ object LxmlElementIterator, type LxmlElementIteratorType ]:
2702
+ """
2703
+ Dead but public. :)
2704
+ """
2705
+ # we keep Python references here to control GC
2706
+ cdef _Element _node
2707
+ cdef _node_to_node_function _next_element
2708
+ def __iter__(self):
2709
+ return self
2710
+
2711
+ cdef void _storeNext(self, _Element node):
2712
+ cdef xmlNode* c_node
2713
+ c_node = self._next_element(node._c_node)
2714
+ while c_node is not NULL and \
2715
+ self._node_type != 0 and \
2716
+ (<tree.xmlElementType>self._node_type != c_node.type or
2717
+ not _tagMatches(c_node, <const_xmlChar*>self._href, <const_xmlChar*>self._name)):
2718
+ c_node = self._next_element(c_node)
2719
+ if c_node is NULL:
2720
+ self._node = None
2721
+ else:
2722
+ # Python ref:
2723
+ self._node = _elementFactory(node._doc, c_node)
2724
+
2725
+ def __next__(self):
2726
+ cdef xmlNode* c_node
2727
+ cdef _Element current_node
2728
+ if self._node is None:
2729
+ raise StopIteration
2730
+ # Python ref:
2731
+ current_node = self._node
2732
+ self._storeNext(current_node)
2733
+ return current_node
2734
+
2735
+ @cython.final
2736
+ @cython.internal
2737
+ cdef class _MultiTagMatcher:
2738
+ """
2739
+ Match an xmlNode against a list of tags.
2740
+ """
2741
+ cdef list _py_tags
2742
+ cdef qname* _cached_tags
2743
+ cdef size_t _tag_count
2744
+ cdef size_t _cached_size
2745
+ cdef _Document _cached_doc
2746
+ cdef int _node_types
2747
+
2748
+ def __cinit__(self, tags):
2749
+ self._py_tags = []
2750
+ self.initTagMatch(tags)
2751
+
2752
+ def __dealloc__(self):
2753
+ self._clear()
2754
+
2755
+ cdef bint rejectsAll(self) noexcept:
2756
+ return not self._tag_count and not self._node_types
2757
+
2758
+ cdef bint rejectsAllAttributes(self) noexcept:
2759
+ return not self._tag_count
2760
+
2761
+ cdef bint matchesType(self, int node_type) noexcept:
2762
+ if node_type == tree.XML_ELEMENT_NODE and self._tag_count:
2763
+ return True
2764
+ return self._node_types & (1 << node_type)
2765
+
2766
+ cdef void _clear(self) noexcept:
2767
+ cdef size_t i, count
2768
+ count = self._tag_count
2769
+ self._tag_count = 0
2770
+ if self._cached_tags:
2771
+ for i in range(count):
2772
+ cpython.ref.Py_XDECREF(self._cached_tags[i].href)
2773
+ python.lxml_free(self._cached_tags)
2774
+ self._cached_tags = NULL
2775
+
2776
+ cdef initTagMatch(self, tags):
2777
+ self._cached_doc = None
2778
+ del self._py_tags[:]
2779
+ self._clear()
2780
+ if tags is None or tags == ():
2781
+ # no selection in tags argument => match anything
2782
+ self._node_types = (
2783
+ 1 << tree.XML_COMMENT_NODE |
2784
+ 1 << tree.XML_PI_NODE |
2785
+ 1 << tree.XML_ENTITY_REF_NODE |
2786
+ 1 << tree.XML_ELEMENT_NODE)
2787
+ else:
2788
+ self._node_types = 0
2789
+ self._storeTags(tags, set())
2790
+
2791
+ cdef _storeTags(self, tag, set seen):
2792
+ if tag is Comment:
2793
+ self._node_types |= 1 << tree.XML_COMMENT_NODE
2794
+ elif tag is ProcessingInstruction:
2795
+ self._node_types |= 1 << tree.XML_PI_NODE
2796
+ elif tag is Entity:
2797
+ self._node_types |= 1 << tree.XML_ENTITY_REF_NODE
2798
+ elif tag is Element:
2799
+ self._node_types |= 1 << tree.XML_ELEMENT_NODE
2800
+ elif python._isString(tag):
2801
+ if tag in seen:
2802
+ return
2803
+ seen.add(tag)
2804
+ if tag in ('*', '{*}*'):
2805
+ self._node_types |= 1 << tree.XML_ELEMENT_NODE
2806
+ else:
2807
+ href, name = _getNsTag(tag)
2808
+ if name == b'*':
2809
+ name = None
2810
+ if href is None:
2811
+ href = b'' # no namespace
2812
+ elif href == b'*':
2813
+ href = None # wildcard: any namespace, including none
2814
+ self._py_tags.append((href, name))
2815
+ elif isinstance(tag, QName):
2816
+ self._storeTags(tag.text, seen)
2817
+ else:
2818
+ # support a sequence of tags
2819
+ for item in tag:
2820
+ self._storeTags(item, seen)
2821
+
2822
+ cdef inline int cacheTags(self, _Document doc, bint force_into_dict=False) except -1:
2823
+ """
2824
+ Look up the tag names in the doc dict to enable string pointer comparisons.
2825
+ """
2826
+ cdef size_t dict_size = tree.xmlDictSize(doc._c_doc.dict)
2827
+ if doc is self._cached_doc and dict_size == self._cached_size:
2828
+ # doc and dict didn't change => names already cached
2829
+ return 0
2830
+ self._tag_count = 0
2831
+ if not self._py_tags:
2832
+ self._cached_doc = doc
2833
+ self._cached_size = dict_size
2834
+ return 0
2835
+ if not self._cached_tags:
2836
+ self._cached_tags = <qname*>python.lxml_malloc(len(self._py_tags), sizeof(qname))
2837
+ if not self._cached_tags:
2838
+ self._cached_doc = None
2839
+ raise MemoryError()
2840
+ self._tag_count = <size_t>_mapTagsToQnameMatchArray(
2841
+ doc._c_doc, self._py_tags, self._cached_tags, force_into_dict)
2842
+ self._cached_doc = doc
2843
+ self._cached_size = dict_size
2844
+ return 0
2845
+
2846
+ cdef inline bint matches(self, xmlNode* c_node) noexcept:
2847
+ cdef qname* c_qname
2848
+ if self._node_types & (1 << c_node.type):
2849
+ return True
2850
+ elif c_node.type == tree.XML_ELEMENT_NODE:
2851
+ for c_qname in self._cached_tags[:self._tag_count]:
2852
+ if _tagMatchesExactly(c_node, c_qname):
2853
+ return True
2854
+ return False
2855
+
2856
+ cdef inline bint matchesNsTag(self, const_xmlChar* c_href,
2857
+ const_xmlChar* c_name) noexcept:
2858
+ cdef qname* c_qname
2859
+ if self._node_types & (1 << tree.XML_ELEMENT_NODE):
2860
+ return True
2861
+ for c_qname in self._cached_tags[:self._tag_count]:
2862
+ if _nsTagMatchesExactly(c_href, c_name, c_qname):
2863
+ return True
2864
+ return False
2865
+
2866
+ cdef inline bint matchesAttribute(self, xmlAttr* c_attr) noexcept:
2867
+ """Attribute matches differ from Element matches in that they do
2868
+ not care about node types.
2869
+ """
2870
+ cdef qname* c_qname
2871
+ for c_qname in self._cached_tags[:self._tag_count]:
2872
+ if _tagMatchesExactly(<xmlNode*>c_attr, c_qname):
2873
+ return True
2874
+ return False
2875
+
2876
+ cdef class _ElementMatchIterator:
2877
+ cdef _Element _node
2878
+ cdef _node_to_node_function _next_element
2879
+ cdef _MultiTagMatcher _matcher
2880
+
2881
+ @cython.final
2882
+ cdef _initTagMatcher(self, tags):
2883
+ self._matcher = _MultiTagMatcher.__new__(_MultiTagMatcher, tags)
2884
+
2885
+ def __iter__(self):
2886
+ return self
2887
+
2888
+ @cython.final
2889
+ cdef int _storeNext(self, _Element node) except -1:
2890
+ self._matcher.cacheTags(node._doc)
2891
+ c_node = self._next_element(node._c_node)
2892
+ while c_node is not NULL and not self._matcher.matches(c_node):
2893
+ c_node = self._next_element(c_node)
2894
+ # store Python ref to next node to make sure it's kept alive
2895
+ self._node = _elementFactory(node._doc, c_node) if c_node is not NULL else None
2896
+ return 0
2897
+
2898
+ def __next__(self):
2899
+ cdef _Element current_node = self._node
2900
+ if current_node is None:
2901
+ raise StopIteration
2902
+ self._storeNext(current_node)
2903
+ return current_node
2904
+
2905
+ cdef class ElementChildIterator(_ElementMatchIterator):
2906
+ """ElementChildIterator(self, node, tag=None, reversed=False)
2907
+ Iterates over the children of an element.
2908
+ """
2909
+ def __cinit__(self, _Element node not None, tag=None, *, bint reversed=False):
2910
+ cdef xmlNode* c_node
2911
+ _assertValidNode(node)
2912
+ self._initTagMatcher(tag)
2913
+ if reversed:
2914
+ c_node = _findChildBackwards(node._c_node, 0)
2915
+ self._next_element = _previousElement
2916
+ else:
2917
+ c_node = _findChildForwards(node._c_node, 0)
2918
+ self._next_element = _nextElement
2919
+ self._matcher.cacheTags(node._doc)
2920
+ while c_node is not NULL and not self._matcher.matches(c_node):
2921
+ c_node = self._next_element(c_node)
2922
+ # store Python ref to next node to make sure it's kept alive
2923
+ self._node = _elementFactory(node._doc, c_node) if c_node is not NULL else None
2924
+
2925
+ cdef class SiblingsIterator(_ElementMatchIterator):
2926
+ """SiblingsIterator(self, node, tag=None, preceding=False)
2927
+ Iterates over the siblings of an element.
2928
+
2929
+ You can pass the boolean keyword ``preceding`` to specify the direction.
2930
+ """
2931
+ def __cinit__(self, _Element node not None, tag=None, *, bint preceding=False):
2932
+ _assertValidNode(node)
2933
+ self._initTagMatcher(tag)
2934
+ if preceding:
2935
+ self._next_element = _previousElement
2936
+ else:
2937
+ self._next_element = _nextElement
2938
+ self._storeNext(node)
2939
+
2940
+ cdef class AncestorsIterator(_ElementMatchIterator):
2941
+ """AncestorsIterator(self, node, tag=None)
2942
+ Iterates over the ancestors of an element (from parent to parent).
2943
+ """
2944
+ def __cinit__(self, _Element node not None, tag=None):
2945
+ _assertValidNode(node)
2946
+ self._initTagMatcher(tag)
2947
+ self._next_element = _parentElement
2948
+ self._storeNext(node)
2949
+
2950
+ cdef class ElementDepthFirstIterator:
2951
+ """ElementDepthFirstIterator(self, node, tag=None, inclusive=True)
2952
+ Iterates over an element and its sub-elements in document order (depth
2953
+ first pre-order).
2954
+
2955
+ Note that this also includes comments, entities and processing
2956
+ instructions. To filter them out, check if the ``tag`` property
2957
+ of the returned element is a string (i.e. not None and not a
2958
+ factory function), or pass the ``Element`` factory for the ``tag``
2959
+ argument to receive only Elements.
2960
+
2961
+ If the optional ``tag`` argument is not None, the iterator returns only
2962
+ the elements that match the respective name and namespace.
2963
+
2964
+ The optional boolean argument 'inclusive' defaults to True and can be set
2965
+ to False to exclude the start element itself.
2966
+
2967
+ Note that the behaviour of this iterator is completely undefined if the
2968
+ tree it traverses is modified during iteration.
2969
+ """
2970
+ # we keep Python references here to control GC
2971
+ # keep the next Element after the one we return, and the (s)top node
2972
+ cdef _Element _next_node
2973
+ cdef _Element _top_node
2974
+ cdef _MultiTagMatcher _matcher
2975
+ def __cinit__(self, _Element node not None, tag=None, *, bint inclusive=True):
2976
+ _assertValidNode(node)
2977
+ self._top_node = node
2978
+ self._next_node = node
2979
+ self._matcher = _MultiTagMatcher.__new__(_MultiTagMatcher, tag)
2980
+ self._matcher.cacheTags(node._doc)
2981
+ if not inclusive or not self._matcher.matches(node._c_node):
2982
+ # find start node (this cannot raise StopIteration, self._next_node != None)
2983
+ next(self)
2984
+
2985
+ def __iter__(self):
2986
+ return self
2987
+
2988
+ def __next__(self):
2989
+ cdef xmlNode* c_node
2990
+ cdef _Element current_node = self._next_node
2991
+ if current_node is None:
2992
+ raise StopIteration
2993
+ c_node = current_node._c_node
2994
+ self._matcher.cacheTags(current_node._doc)
2995
+ if not self._matcher._tag_count:
2996
+ # no tag name was found in the dict => not in document either
2997
+ # try to match by node type
2998
+ c_node = self._nextNodeAnyTag(c_node)
2999
+ else:
3000
+ c_node = self._nextNodeMatchTag(c_node)
3001
+ if c_node is NULL:
3002
+ self._next_node = None
3003
+ else:
3004
+ self._next_node = _elementFactory(current_node._doc, c_node)
3005
+ return current_node
3006
+
3007
+ @cython.final
3008
+ cdef xmlNode* _nextNodeAnyTag(self, xmlNode* c_node) noexcept:
3009
+ cdef int node_types = self._matcher._node_types
3010
+ if not node_types:
3011
+ return NULL
3012
+ tree.BEGIN_FOR_EACH_ELEMENT_FROM(self._top_node._c_node, c_node, 0)
3013
+ if node_types & (1 << c_node.type):
3014
+ return c_node
3015
+ tree.END_FOR_EACH_ELEMENT_FROM(c_node)
3016
+ return NULL
3017
+
3018
+ @cython.final
3019
+ cdef xmlNode* _nextNodeMatchTag(self, xmlNode* c_node) noexcept:
3020
+ tree.BEGIN_FOR_EACH_ELEMENT_FROM(self._top_node._c_node, c_node, 0)
3021
+ if self._matcher.matches(c_node):
3022
+ return c_node
3023
+ tree.END_FOR_EACH_ELEMENT_FROM(c_node)
3024
+ return NULL
3025
+
3026
+
3027
+ cdef class ElementTextIterator:
3028
+ """ElementTextIterator(self, element, tag=None, with_tail=True)
3029
+ Iterates over the text content of a subtree.
3030
+
3031
+ You can pass the ``tag`` keyword argument to restrict text content to a
3032
+ specific tag name.
3033
+
3034
+ You can set the ``with_tail`` keyword argument to ``False`` to skip over
3035
+ tail text (e.g. if you know that it's only whitespace from pretty-printing).
3036
+ """
3037
+ cdef object _events
3038
+ cdef _Element _start_element
3039
+ def __cinit__(self, _Element element not None, tag=None, *, bint with_tail=True):
3040
+ _assertValidNode(element)
3041
+ if with_tail:
3042
+ events = ("start", "comment", "pi", "end")
3043
+ else:
3044
+ events = ("start",)
3045
+ self._start_element = element
3046
+ self._events = iterwalk(element, events=events, tag=tag)
3047
+
3048
+ def __iter__(self):
3049
+ return self
3050
+
3051
+ def __next__(self):
3052
+ cdef _Element element
3053
+ result = None
3054
+ while result is None:
3055
+ event, element = next(self._events) # raises StopIteration
3056
+ if event == "start":
3057
+ result = element.text
3058
+ elif element is not self._start_element:
3059
+ result = element.tail
3060
+ return result
3061
+
3062
+
3063
+ cdef xmlNode* _createElement(xmlDoc* c_doc, object name_utf) except NULL:
3064
+ cdef xmlNode* c_node
3065
+ c_node = tree.xmlNewDocNode(c_doc, NULL, _xcstr(name_utf), NULL)
3066
+ return c_node
3067
+
3068
+ cdef xmlNode* _createComment(xmlDoc* c_doc, const_xmlChar* text) noexcept:
3069
+ cdef xmlNode* c_node
3070
+ c_node = tree.xmlNewDocComment(c_doc, text)
3071
+ return c_node
3072
+
3073
+ cdef xmlNode* _createPI(xmlDoc* c_doc, const_xmlChar* target, const_xmlChar* text) noexcept:
3074
+ cdef xmlNode* c_node
3075
+ c_node = tree.xmlNewDocPI(c_doc, target, text)
3076
+ return c_node
3077
+
3078
+ cdef xmlNode* _createEntity(xmlDoc* c_doc, const_xmlChar* name) noexcept:
3079
+ cdef xmlNode* c_node
3080
+ c_node = tree.xmlNewReference(c_doc, name)
3081
+ return c_node
3082
+
3083
+ # module-level API for ElementTree
3084
+
3085
+ def Element(_tag, attrib=None, nsmap=None, **_extra):
3086
+ """Element(_tag, attrib=None, nsmap=None, **_extra)
3087
+
3088
+ Element factory. This function returns an object implementing the
3089
+ Element interface.
3090
+
3091
+ Also look at the `_Element.makeelement()` and
3092
+ `_BaseParser.makeelement()` methods, which provide a faster way to
3093
+ create an Element within a specific document or parser context.
3094
+ """
3095
+ return _makeElement(_tag, NULL, None, None, None, None,
3096
+ attrib, nsmap, _extra)
3097
+
3098
+
3099
+ def Comment(text=None):
3100
+ """Comment(text=None)
3101
+
3102
+ Comment element factory. This factory function creates a special element that will
3103
+ be serialized as an XML comment.
3104
+ """
3105
+ cdef _Document doc
3106
+ cdef xmlNode* c_node
3107
+ cdef xmlDoc* c_doc
3108
+
3109
+ if text is None:
3110
+ text = b''
3111
+ else:
3112
+ text = _utf8(text)
3113
+ if b'--' in text or text.endswith(b'-'):
3114
+ raise ValueError("Comment may not contain '--' or end with '-'")
3115
+
3116
+ c_doc = _newXMLDoc()
3117
+ doc = _documentFactory(c_doc, None)
3118
+ c_node = _createComment(c_doc, _xcstr(text))
3119
+ tree.xmlAddChild(<xmlNode*>c_doc, c_node)
3120
+ return _elementFactory(doc, c_node)
3121
+
3122
+
3123
+ def ProcessingInstruction(target, text=None):
3124
+ """ProcessingInstruction(target, text=None)
3125
+
3126
+ ProcessingInstruction element factory. This factory function creates a
3127
+ special element that will be serialized as an XML processing instruction.
3128
+ """
3129
+ cdef _Document doc
3130
+ cdef xmlNode* c_node
3131
+ cdef xmlDoc* c_doc
3132
+
3133
+ target = _utf8(target)
3134
+ _tagValidOrRaise(target)
3135
+ if target.lower() == b'xml':
3136
+ raise ValueError, f"Invalid PI name '{target}'"
3137
+
3138
+ if text is None:
3139
+ text = b''
3140
+ else:
3141
+ text = _utf8(text)
3142
+ if b'?>' in text:
3143
+ raise ValueError, "PI text must not contain '?>'"
3144
+
3145
+ c_doc = _newXMLDoc()
3146
+ doc = _documentFactory(c_doc, None)
3147
+ c_node = _createPI(c_doc, _xcstr(target), _xcstr(text))
3148
+ tree.xmlAddChild(<xmlNode*>c_doc, c_node)
3149
+ return _elementFactory(doc, c_node)
3150
+
3151
+ PI = ProcessingInstruction
3152
+
3153
+
3154
+ cdef class CDATA:
3155
+ """CDATA(data)
3156
+
3157
+ CDATA factory. This factory creates an opaque data object that
3158
+ can be used to set Element text. The usual way to use it is::
3159
+
3160
+ >>> el = Element('content')
3161
+ >>> el.text = CDATA('a string')
3162
+
3163
+ >>> print(el.text)
3164
+ a string
3165
+ >>> print(tostring(el, encoding="unicode"))
3166
+ <content><![CDATA[a string]]></content>
3167
+ """
3168
+ cdef bytes _utf8_data
3169
+ def __cinit__(self, data):
3170
+ self._utf8_data = _utf8(data)
3171
+
3172
+
3173
+ def Entity(name):
3174
+ """Entity(name)
3175
+
3176
+ Entity factory. This factory function creates a special element
3177
+ that will be serialized as an XML entity reference or character
3178
+ reference. Note, however, that entities will not be automatically
3179
+ declared in the document. A document that uses entity references
3180
+ requires a DTD to define the entities.
3181
+ """
3182
+ cdef _Document doc
3183
+ cdef xmlNode* c_node
3184
+ cdef xmlDoc* c_doc
3185
+ name_utf = _utf8(name)
3186
+ c_name = _xcstr(name_utf)
3187
+ if c_name[0] == c'#':
3188
+ if not _characterReferenceIsValid(c_name + 1):
3189
+ raise ValueError, f"Invalid character reference: '{name}'"
3190
+ elif not _xmlNameIsValid(c_name):
3191
+ raise ValueError, f"Invalid entity reference: '{name}'"
3192
+ c_doc = _newXMLDoc()
3193
+ doc = _documentFactory(c_doc, None)
3194
+ c_node = _createEntity(c_doc, c_name)
3195
+ tree.xmlAddChild(<xmlNode*>c_doc, c_node)
3196
+ return _elementFactory(doc, c_node)
3197
+
3198
+
3199
+ def SubElement(_Element _parent not None, _tag,
3200
+ attrib=None, nsmap=None, **_extra):
3201
+ """SubElement(_parent, _tag, attrib=None, nsmap=None, **_extra)
3202
+
3203
+ Subelement factory. This function creates an element instance, and
3204
+ appends it to an existing element.
3205
+ """
3206
+ return _makeSubElement(_parent, _tag, None, None, attrib, nsmap, _extra)
3207
+
3208
+
3209
+ def ElementTree(_Element element=None, *, file=None, _BaseParser parser=None):
3210
+ """ElementTree(element=None, file=None, parser=None)
3211
+
3212
+ ElementTree wrapper class.
3213
+ """
3214
+ cdef xmlNode* c_next
3215
+ cdef xmlNode* c_node
3216
+ cdef xmlNode* c_node_copy
3217
+ cdef xmlDoc* c_doc
3218
+ cdef _ElementTree etree
3219
+ cdef _Document doc
3220
+
3221
+ if element is not None:
3222
+ doc = element._doc
3223
+ elif file is not None:
3224
+ try:
3225
+ doc = _parseDocument(file, parser, None)
3226
+ except _TargetParserResult as result_container:
3227
+ return result_container.result
3228
+ else:
3229
+ c_doc = _newXMLDoc()
3230
+ doc = _documentFactory(c_doc, parser)
3231
+
3232
+ return _elementTreeFactory(doc, element)
3233
+
3234
+
3235
+ def HTML(text, _BaseParser parser=None, *, base_url=None):
3236
+ """HTML(text, parser=None, base_url=None)
3237
+
3238
+ Parses an HTML document from a string constant. Returns the root
3239
+ node (or the result returned by a parser target). This function
3240
+ can be used to embed "HTML literals" in Python code.
3241
+
3242
+ To override the parser with a different ``HTMLParser`` you can pass it to
3243
+ the ``parser`` keyword argument.
3244
+
3245
+ The ``base_url`` keyword argument allows to set the original base URL of
3246
+ the document to support relative Paths when looking up external entities
3247
+ (DTD, XInclude, ...).
3248
+ """
3249
+ cdef _Document doc
3250
+ if parser is None:
3251
+ parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
3252
+ if not isinstance(parser, HTMLParser):
3253
+ parser = __DEFAULT_HTML_PARSER
3254
+ try:
3255
+ doc = _parseMemoryDocument(text, base_url, parser)
3256
+ return doc.getroot()
3257
+ except _TargetParserResult as result_container:
3258
+ return result_container.result
3259
+
3260
+
3261
+ def XML(text, _BaseParser parser=None, *, base_url=None):
3262
+ """XML(text, parser=None, base_url=None)
3263
+
3264
+ Parses an XML document or fragment from a string constant.
3265
+ Returns the root node (or the result returned by a parser target).
3266
+ This function can be used to embed "XML literals" in Python code,
3267
+ like in
3268
+
3269
+ >>> root = XML("<root><test/></root>")
3270
+ >>> print(root.tag)
3271
+ root
3272
+
3273
+ To override the parser with a different ``XMLParser`` you can pass it to
3274
+ the ``parser`` keyword argument.
3275
+
3276
+ The ``base_url`` keyword argument allows to set the original base URL of
3277
+ the document to support relative Paths when looking up external entities
3278
+ (DTD, XInclude, ...).
3279
+ """
3280
+ cdef _Document doc
3281
+ if parser is None:
3282
+ parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
3283
+ if not isinstance(parser, XMLParser):
3284
+ parser = __DEFAULT_XML_PARSER
3285
+ try:
3286
+ doc = _parseMemoryDocument(text, base_url, parser)
3287
+ return doc.getroot()
3288
+ except _TargetParserResult as result_container:
3289
+ return result_container.result
3290
+
3291
+
3292
+ def fromstring(text, _BaseParser parser=None, *, base_url=None):
3293
+ """fromstring(text, parser=None, base_url=None)
3294
+
3295
+ Parses an XML document or fragment from a string. Returns the
3296
+ root node (or the result returned by a parser target).
3297
+
3298
+ To override the default parser with a different parser you can pass it to
3299
+ the ``parser`` keyword argument.
3300
+
3301
+ The ``base_url`` keyword argument allows to set the original base URL of
3302
+ the document to support relative Paths when looking up external entities
3303
+ (DTD, XInclude, ...).
3304
+ """
3305
+ cdef _Document doc
3306
+ try:
3307
+ doc = _parseMemoryDocument(text, base_url, parser)
3308
+ return doc.getroot()
3309
+ except _TargetParserResult as result_container:
3310
+ return result_container.result
3311
+
3312
+
3313
+ def fromstringlist(strings, _BaseParser parser=None):
3314
+ """fromstringlist(strings, parser=None)
3315
+
3316
+ Parses an XML document from a sequence of strings. Returns the
3317
+ root node (or the result returned by a parser target).
3318
+
3319
+ To override the default parser with a different parser you can pass it to
3320
+ the ``parser`` keyword argument.
3321
+ """
3322
+ cdef _Document doc
3323
+ if isinstance(strings, (bytes, unicode)):
3324
+ raise ValueError("passing a single string into fromstringlist() is not"
3325
+ " efficient, use fromstring() instead")
3326
+ if parser is None:
3327
+ parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
3328
+ feed = parser.feed
3329
+ for data in strings:
3330
+ feed(data)
3331
+ return parser.close()
3332
+
3333
+
3334
+ def iselement(element):
3335
+ """iselement(element)
3336
+
3337
+ Checks if an object appears to be a valid element object.
3338
+ """
3339
+ return isinstance(element, _Element) and (<_Element>element)._c_node is not NULL
3340
+
3341
+
3342
+ def indent(tree, space=" ", *, Py_ssize_t level=0):
3343
+ """indent(tree, space=" ", level=0)
3344
+
3345
+ Indent an XML document by inserting newlines and indentation space
3346
+ after elements.
3347
+
3348
+ *tree* is the ElementTree or Element to modify. The (root) element
3349
+ itself will not be changed, but the tail text of all elements in its
3350
+ subtree will be adapted.
3351
+
3352
+ *space* is the whitespace to insert for each indentation level, two
3353
+ space characters by default.
3354
+
3355
+ *level* is the initial indentation level. Setting this to a higher
3356
+ value than 0 can be used for indenting subtrees that are more deeply
3357
+ nested inside of a document.
3358
+ """
3359
+ root = _rootNodeOrRaise(tree)
3360
+ if level < 0:
3361
+ raise ValueError(f"Initial indentation level must be >= 0, got {level}")
3362
+ if _hasChild(root._c_node):
3363
+ space = _utf8(space)
3364
+ indent = b"\n" + level * space
3365
+ _indent_children(root._c_node, 1, space, [indent, indent + space])
3366
+
3367
+
3368
+ cdef int _indent_children(xmlNode* c_node, Py_ssize_t level, bytes one_space, list indentations) except -1:
3369
+ # Reuse indentation strings for speed.
3370
+ if len(indentations) <= level:
3371
+ indentations.append(indentations[-1] + one_space)
3372
+
3373
+ # Start a new indentation level for the first child.
3374
+ child_indentation = indentations[level]
3375
+ if not _hasNonWhitespaceText(c_node):
3376
+ _setNodeText(c_node, child_indentation)
3377
+
3378
+ # Recursively indent all children.
3379
+ cdef xmlNode* c_child = _findChildForwards(c_node, 0)
3380
+ while c_child is not NULL:
3381
+ if _hasChild(c_child):
3382
+ _indent_children(c_child, level+1, one_space, indentations)
3383
+ c_next_child = _nextElement(c_child)
3384
+ if not _hasNonWhitespaceTail(c_child):
3385
+ if c_next_child is NULL:
3386
+ # Dedent after the last child.
3387
+ child_indentation = indentations[level-1]
3388
+ _setTailText(c_child, child_indentation)
3389
+ c_child = c_next_child
3390
+ return 0
3391
+
3392
+
3393
+ def dump(_Element elem not None, *, bint pretty_print=True, bint with_tail=True):
3394
+ """dump(elem, pretty_print=True, with_tail=True)
3395
+
3396
+ Writes an element tree or element structure to sys.stdout. This function
3397
+ should be used for debugging only.
3398
+ """
3399
+ xml = tostring(elem, pretty_print=pretty_print, with_tail=with_tail, encoding='unicode')
3400
+ if not pretty_print:
3401
+ xml += '\n'
3402
+ sys.stdout.write(xml)
3403
+
3404
+
3405
+ def tostring(element_or_tree, *, encoding=None, method="xml",
3406
+ xml_declaration=None, bint pretty_print=False, bint with_tail=True,
3407
+ standalone=None, doctype=None,
3408
+ # method='c14n'
3409
+ bint exclusive=False, inclusive_ns_prefixes=None,
3410
+ # method='c14n2'
3411
+ bint with_comments=True, bint strip_text=False,
3412
+ ):
3413
+ """tostring(element_or_tree, encoding=None, method="xml",
3414
+ xml_declaration=None, pretty_print=False, with_tail=True,
3415
+ standalone=None, doctype=None,
3416
+ exclusive=False, inclusive_ns_prefixes=None,
3417
+ with_comments=True, strip_text=False,
3418
+ )
3419
+
3420
+ Serialize an element to an encoded string representation of its XML
3421
+ tree.
3422
+
3423
+ Defaults to ASCII encoding without XML declaration. This
3424
+ behaviour can be configured with the keyword arguments 'encoding'
3425
+ (string) and 'xml_declaration' (bool). Note that changing the
3426
+ encoding to a non UTF-8 compatible encoding will enable a
3427
+ declaration by default.
3428
+
3429
+ You can also serialise to a Unicode string without declaration by
3430
+ passing the name ``'unicode'`` as encoding (or the ``str`` function
3431
+ in Py3 or ``unicode`` in Py2). This changes the return value from
3432
+ a byte string to an unencoded unicode string.
3433
+
3434
+ The keyword argument 'pretty_print' (bool) enables formatted XML.
3435
+
3436
+ The keyword argument 'method' selects the output method: 'xml',
3437
+ 'html', plain 'text' (text content without tags), 'c14n' or 'c14n2'.
3438
+ Default is 'xml'.
3439
+
3440
+ With ``method="c14n"`` (C14N version 1), the options ``exclusive``,
3441
+ ``with_comments`` and ``inclusive_ns_prefixes`` request exclusive
3442
+ C14N, include comments, and list the inclusive prefixes respectively.
3443
+
3444
+ With ``method="c14n2"`` (C14N version 2), the ``with_comments`` and
3445
+ ``strip_text`` options control the output of comments and text space
3446
+ according to C14N 2.0.
3447
+
3448
+ Passing a boolean value to the ``standalone`` option will output
3449
+ an XML declaration with the corresponding ``standalone`` flag.
3450
+
3451
+ The ``doctype`` option allows passing in a plain string that will
3452
+ be serialised before the XML tree. Note that passing in non
3453
+ well-formed content here will make the XML output non well-formed.
3454
+ Also, an existing doctype in the document tree will not be removed
3455
+ when serialising an ElementTree instance.
3456
+
3457
+ You can prevent the tail text of the element from being serialised
3458
+ by passing the boolean ``with_tail`` option. This has no impact
3459
+ on the tail text of children, which will always be serialised.
3460
+ """
3461
+ cdef bint write_declaration
3462
+ cdef int is_standalone
3463
+ # C14N serialisation
3464
+ if method in ('c14n', 'c14n2'):
3465
+ if encoding is not None:
3466
+ raise ValueError("Cannot specify encoding with C14N")
3467
+ if xml_declaration:
3468
+ raise ValueError("Cannot enable XML declaration in C14N")
3469
+ if method == 'c14n':
3470
+ return _tostringC14N(element_or_tree, exclusive, with_comments, inclusive_ns_prefixes)
3471
+ else:
3472
+ out = BytesIO()
3473
+ target = C14NWriterTarget(
3474
+ utf8_writer(out).write,
3475
+ with_comments=with_comments, strip_text=strip_text)
3476
+ _tree_to_target(element_or_tree, target)
3477
+ return out.getvalue()
3478
+ if not with_comments:
3479
+ raise ValueError("Can only discard comments in C14N serialisation")
3480
+ if strip_text:
3481
+ raise ValueError("Can only strip text in C14N 2.0 serialisation")
3482
+ if encoding is unicode or (encoding is not None and encoding.lower() == 'unicode'):
3483
+ if xml_declaration:
3484
+ raise ValueError, \
3485
+ "Serialisation to unicode must not request an XML declaration"
3486
+ write_declaration = 0
3487
+ encoding = unicode
3488
+ elif xml_declaration is None:
3489
+ # by default, write an XML declaration only for non-standard encodings
3490
+ write_declaration = encoding is not None and encoding.upper() not in \
3491
+ ('ASCII', 'UTF-8', 'UTF8', 'US-ASCII')
3492
+ else:
3493
+ write_declaration = xml_declaration
3494
+ if encoding is None:
3495
+ encoding = 'ASCII'
3496
+ if standalone is None:
3497
+ is_standalone = -1
3498
+ elif standalone:
3499
+ write_declaration = 1
3500
+ is_standalone = 1
3501
+ else:
3502
+ write_declaration = 1
3503
+ is_standalone = 0
3504
+
3505
+ if isinstance(element_or_tree, _Element):
3506
+ return _tostring(<_Element>element_or_tree, encoding, doctype, method,
3507
+ write_declaration, 0, pretty_print, with_tail,
3508
+ is_standalone)
3509
+ elif isinstance(element_or_tree, _ElementTree):
3510
+ return _tostring((<_ElementTree>element_or_tree)._context_node,
3511
+ encoding, doctype, method, write_declaration, 1,
3512
+ pretty_print, with_tail, is_standalone)
3513
+ else:
3514
+ raise TypeError, f"Type '{python._fqtypename(element_or_tree).decode('utf8')}' cannot be serialized."
3515
+
3516
+
3517
+
3518
+ def tostringlist(element_or_tree, *args, **kwargs):
3519
+ """tostringlist(element_or_tree, *args, **kwargs)
3520
+
3521
+ Serialize an element to an encoded string representation of its XML
3522
+ tree, stored in a list of partial strings.
3523
+
3524
+ This is purely for ElementTree 1.3 compatibility. The result is a
3525
+ single string wrapped in a list.
3526
+ """
3527
+ return [tostring(element_or_tree, *args, **kwargs)]
3528
+
3529
+
3530
+ def tounicode(element_or_tree, *, method="xml", bint pretty_print=False,
3531
+ bint with_tail=True, doctype=None):
3532
+ """tounicode(element_or_tree, method="xml", pretty_print=False,
3533
+ with_tail=True, doctype=None)
3534
+
3535
+ Serialize an element to the Python unicode representation of its XML
3536
+ tree.
3537
+
3538
+ :deprecated: use ``tostring(el, encoding='unicode')`` instead.
3539
+
3540
+ Note that the result does not carry an XML encoding declaration and is
3541
+ therefore not necessarily suited for serialization to byte streams without
3542
+ further treatment.
3543
+
3544
+ The boolean keyword argument 'pretty_print' enables formatted XML.
3545
+
3546
+ The keyword argument 'method' selects the output method: 'xml',
3547
+ 'html' or plain 'text'.
3548
+
3549
+ You can prevent the tail text of the element from being serialised
3550
+ by passing the boolean ``with_tail`` option. This has no impact
3551
+ on the tail text of children, which will always be serialised.
3552
+ """
3553
+ if isinstance(element_or_tree, _Element):
3554
+ return _tostring(<_Element>element_or_tree, unicode, doctype, method,
3555
+ 0, 0, pretty_print, with_tail, -1)
3556
+ elif isinstance(element_or_tree, _ElementTree):
3557
+ return _tostring((<_ElementTree>element_or_tree)._context_node,
3558
+ unicode, doctype, method, 0, 1, pretty_print,
3559
+ with_tail, -1)
3560
+ else:
3561
+ raise TypeError, f"Type '{type(element_or_tree)}' cannot be serialized."
3562
+
3563
+
3564
+ def parse(source, _BaseParser parser=None, *, base_url=None):
3565
+ """parse(source, parser=None, base_url=None)
3566
+
3567
+ Return an ElementTree object loaded with source elements. If no parser
3568
+ is provided as second argument, the default parser is used.
3569
+
3570
+ The ``source`` can be any of the following:
3571
+
3572
+ - a file name/path
3573
+ - a file object
3574
+ - a file-like object
3575
+ - a URL using the HTTP or FTP protocol
3576
+
3577
+ To parse from a string, use the ``fromstring()`` function instead.
3578
+
3579
+ Note that it is generally faster to parse from a file path or URL
3580
+ than from an open file object or file-like object. Transparent
3581
+ decompression from gzip compressed sources is supported (unless
3582
+ explicitly disabled in libxml2).
3583
+
3584
+ The ``base_url`` keyword allows setting a URL for the document
3585
+ when parsing from a file-like object. This is needed when looking
3586
+ up external entities (DTD, XInclude, ...) with relative paths.
3587
+ """
3588
+ cdef _Document doc
3589
+ try:
3590
+ doc = _parseDocument(source, parser, base_url)
3591
+ return _elementTreeFactory(doc, None)
3592
+ except _TargetParserResult as result_container:
3593
+ return result_container.result
3594
+
3595
+
3596
+ def adopt_external_document(capsule, _BaseParser parser=None):
3597
+ """adopt_external_document(capsule, parser=None)
3598
+
3599
+ Unpack a libxml2 document pointer from a PyCapsule and wrap it in an
3600
+ lxml ElementTree object.
3601
+
3602
+ This allows external libraries to build XML/HTML trees using libxml2
3603
+ and then pass them efficiently into lxml for further processing.
3604
+
3605
+ If a ``parser`` is provided, it will be used for configuring the
3606
+ lxml document. No parsing will be done.
3607
+
3608
+ The capsule must have the name ``"libxml2:xmlDoc"`` and its pointer
3609
+ value must reference a correct libxml2 document of type ``xmlDoc*``.
3610
+ The creator of the capsule must take care to correctly clean up the
3611
+ document using an appropriate capsule destructor. By default, the
3612
+ libxml2 document will be copied to let lxml safely own the memory
3613
+ of the internal tree that it uses.
3614
+
3615
+ If the capsule context is non-NULL, it must point to a C string that
3616
+ can be compared using ``strcmp()``. If the context string equals
3617
+ ``"destructor:xmlFreeDoc"``, the libxml2 document will not be copied
3618
+ but the capsule invalidated instead by clearing its destructor and
3619
+ name. That way, lxml takes ownership of the libxml2 document in memory
3620
+ without creating a copy first, and the capsule destructor will not be
3621
+ called. The document will then eventually be cleaned up by lxml using
3622
+ the libxml2 API function ``xmlFreeDoc()`` once it is no longer used.
3623
+
3624
+ If no copy is made, later modifications of the tree outside of lxml
3625
+ should not be attempted after transferring the ownership.
3626
+ """
3627
+ cdef xmlDoc* c_doc
3628
+ cdef bint is_owned = False
3629
+ c_doc = <xmlDoc*> python.lxml_unpack_xmldoc_capsule(capsule, &is_owned)
3630
+ doc = _adoptForeignDoc(c_doc, parser, is_owned)
3631
+ return _elementTreeFactory(doc, None)
3632
+
3633
+
3634
+ ################################################################################
3635
+ # Include submodules
3636
+
3637
+ include "readonlytree.pxi" # Read-only implementation of Element proxies
3638
+ include "classlookup.pxi" # Element class lookup mechanisms
3639
+ include "nsclasses.pxi" # Namespace implementation and registry
3640
+ include "docloader.pxi" # Support for custom document loaders
3641
+ include "parser.pxi" # XML and HTML parsers
3642
+ include "saxparser.pxi" # SAX-like Parser interface and tree builder
3643
+ include "parsertarget.pxi" # ET Parser target
3644
+ include "serializer.pxi" # XML output functions
3645
+ include "iterparse.pxi" # incremental XML parsing
3646
+ include "xmlid.pxi" # XMLID and IDDict
3647
+ include "xinclude.pxi" # XInclude
3648
+ include "cleanup.pxi" # Cleanup and recursive element removal functions
3649
+
3650
+
3651
+ ################################################################################
3652
+ # Include submodules for XPath and XSLT
3653
+
3654
+ include "extensions.pxi" # XPath/XSLT extension functions
3655
+ include "xpath.pxi" # XPath evaluation
3656
+ include "xslt.pxi" # XSL transformations
3657
+ include "xsltext.pxi" # XSL extension elements
3658
+
3659
+
3660
+ ################################################################################
3661
+ # Validation
3662
+
3663
+ cdef class DocumentInvalid(LxmlError):
3664
+ """Validation error.
3665
+
3666
+ Raised by all document validators when their ``assertValid(tree)``
3667
+ method fails.
3668
+ """
3669
+
3670
+
3671
+ cdef class _Validator:
3672
+ "Base class for XML validators."
3673
+ cdef _ErrorLog _error_log
3674
+ def __cinit__(self):
3675
+ self._error_log = _ErrorLog()
3676
+
3677
+ def validate(self, etree):
3678
+ """validate(self, etree)
3679
+
3680
+ Validate the document using this schema.
3681
+
3682
+ Returns true if document is valid, false if not.
3683
+ """
3684
+ return self(etree)
3685
+
3686
+ def assertValid(self, etree):
3687
+ """assertValid(self, etree)
3688
+
3689
+ Raises `DocumentInvalid` if the document does not comply with the schema.
3690
+ """
3691
+ if not self(etree):
3692
+ raise DocumentInvalid(self._error_log._buildExceptionMessage(
3693
+ "Document does not comply with schema"),
3694
+ self._error_log)
3695
+
3696
+ def assert_(self, etree):
3697
+ """assert_(self, etree)
3698
+
3699
+ Raises `AssertionError` if the document does not comply with the schema.
3700
+ """
3701
+ if not self(etree):
3702
+ raise AssertionError, self._error_log._buildExceptionMessage(
3703
+ "Document does not comply with schema")
3704
+
3705
+ cpdef _append_log_message(self, int domain, int type, int level, int line,
3706
+ message, filename):
3707
+ self._error_log._receiveGeneric(domain, type, level, line, message,
3708
+ filename)
3709
+
3710
+ cpdef _clear_error_log(self):
3711
+ self._error_log.clear()
3712
+
3713
+ @property
3714
+ def error_log(self):
3715
+ """The log of validation errors and warnings."""
3716
+ assert self._error_log is not None, "XPath evaluator not initialised"
3717
+ return self._error_log.copy()
3718
+
3719
+ include "dtd.pxi" # DTD
3720
+ include "relaxng.pxi" # RelaxNG
3721
+ include "xmlschema.pxi" # XMLSchema
3722
+ include "schematron.pxi" # Schematron (requires libxml2 2.6.21+)
3723
+
3724
+ ################################################################################
3725
+ # Public C API
3726
+
3727
+ include "public-api.pxi"
3728
+
3729
+ ################################################################################
3730
+ # Other stuff
3731
+
3732
+ include "debug.pxi"