Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- llmeval-env/lib/python3.10/site-packages/lxml/ElementInclude.py +244 -0
- llmeval-env/lib/python3.10/site-packages/lxml/__init__.py +22 -0
- llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/ElementInclude.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/_elementpath.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/builder.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/cssselect.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/doctestcompare.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/pyclasslookup.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/sax.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/usedoctest.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/lxml/builder.cpython-310-x86_64-linux-gnu.so +0 -0
- llmeval-env/lib/python3.10/site-packages/lxml/builder.py +232 -0
- llmeval-env/lib/python3.10/site-packages/lxml/cleanup.pxi +215 -0
- llmeval-env/lib/python3.10/site-packages/lxml/debug.pxi +90 -0
- llmeval-env/lib/python3.10/site-packages/lxml/docloader.pxi +178 -0
- llmeval-env/lib/python3.10/site-packages/lxml/doctestcompare.py +488 -0
- llmeval-env/lib/python3.10/site-packages/lxml/dtd.pxi +478 -0
- llmeval-env/lib/python3.10/site-packages/lxml/etree_api.h +195 -0
- llmeval-env/lib/python3.10/site-packages/lxml/html/__pycache__/_diffcommand.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/lxml/html/__pycache__/_setmixin.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/lxml/html/__pycache__/builder.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/lxml/html/__pycache__/diff.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/lxml/html/__pycache__/soupparser.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/lxml/html/_html5builder.py +100 -0
- llmeval-env/lib/python3.10/site-packages/lxml/html/clean.py +21 -0
- llmeval-env/lib/python3.10/site-packages/lxml/html/diff.cpython-310-x86_64-linux-gnu.so +0 -0
- llmeval-env/lib/python3.10/site-packages/lxml/html/html5parser.py +260 -0
- llmeval-env/lib/python3.10/site-packages/lxml/html/soupparser.py +314 -0
- llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/__init__.py +348 -0
- llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/rng/iso-schematron.rng +709 -0
- llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/RNG2Schtrn.xsl +75 -0
- llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/XSD2Schtrn.xsl +77 -0
- llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_abstract_expand.xsl +313 -0
- llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_dsdl_include.xsl +1160 -0
- llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_message.xsl +55 -0
- llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_skeleton_for_xslt1.xsl +1796 -0
- llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_svrl_for_xslt1.xsl +588 -0
- llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/readme.txt +84 -0
- llmeval-env/lib/python3.10/site-packages/lxml/iterparse.pxi +438 -0
- llmeval-env/lib/python3.10/site-packages/lxml/lxml.etree_api.h +195 -0
- llmeval-env/lib/python3.10/site-packages/lxml/objectify.pyx +2145 -0
- llmeval-env/lib/python3.10/site-packages/lxml/parser.pxi +1994 -0
- llmeval-env/lib/python3.10/site-packages/lxml/public-api.pxi +178 -0
- llmeval-env/lib/python3.10/site-packages/lxml/readonlytree.pxi +565 -0
- llmeval-env/lib/python3.10/site-packages/lxml/relaxng.pxi +165 -0
- llmeval-env/lib/python3.10/site-packages/lxml/sax.py +275 -0
- llmeval-env/lib/python3.10/site-packages/lxml/schematron.pxi +168 -0
- llmeval-env/lib/python3.10/site-packages/lxml/xinclude.pxi +67 -0
llmeval-env/lib/python3.10/site-packages/lxml/ElementInclude.py
ADDED
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# ElementTree
|
3 |
+
# $Id: ElementInclude.py 1862 2004-06-18 07:31:02Z Fredrik $
|
4 |
+
#
|
5 |
+
# limited xinclude support for element trees
|
6 |
+
#
|
7 |
+
# history:
|
8 |
+
# 2003-08-15 fl created
|
9 |
+
# 2003-11-14 fl fixed default loader
|
10 |
+
#
|
11 |
+
# Copyright (c) 2003-2004 by Fredrik Lundh. All rights reserved.
|
12 |
+
#
|
13 | |
14 |
+
# http://www.pythonware.com
|
15 |
+
#
|
16 |
+
# --------------------------------------------------------------------
|
17 |
+
# The ElementTree toolkit is
|
18 |
+
#
|
19 |
+
# Copyright (c) 1999-2004 by Fredrik Lundh
|
20 |
+
#
|
21 |
+
# By obtaining, using, and/or copying this software and/or its
|
22 |
+
# associated documentation, you agree that you have read, understood,
|
23 |
+
# and will comply with the following terms and conditions:
|
24 |
+
#
|
25 |
+
# Permission to use, copy, modify, and distribute this software and
|
26 |
+
# its associated documentation for any purpose and without fee is
|
27 |
+
# hereby granted, provided that the above copyright notice appears in
|
28 |
+
# all copies, and that both that copyright notice and this permission
|
29 |
+
# notice appear in supporting documentation, and that the name of
|
30 |
+
# Secret Labs AB or the author not be used in advertising or publicity
|
31 |
+
# pertaining to distribution of the software without specific, written
|
32 |
+
# prior permission.
|
33 |
+
#
|
34 |
+
# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
|
35 |
+
# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
|
36 |
+
# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
|
37 |
+
# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
|
38 |
+
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
|
39 |
+
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
|
40 |
+
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
|
41 |
+
# OF THIS SOFTWARE.
|
42 |
+
# --------------------------------------------------------------------
|
43 |
+
|
44 |
+
"""
|
45 |
+
Limited XInclude support for the ElementTree package.
|
46 |
+
|
47 |
+
While lxml.etree has full support for XInclude (see
|
48 |
+
`etree.ElementTree.xinclude()`), this module provides a simpler, pure
|
49 |
+
Python, ElementTree compatible implementation that supports a simple
|
50 |
+
form of custom URL resolvers.
|
51 |
+
"""
|
52 |
+
|
53 |
+
from lxml import etree
|
54 |
+
try:
|
55 |
+
from urlparse import urljoin
|
56 |
+
from urllib2 import urlopen
|
57 |
+
except ImportError:
|
58 |
+
# Python 3
|
59 |
+
from urllib.parse import urljoin
|
60 |
+
from urllib.request import urlopen
|
61 |
+
|
62 |
+
XINCLUDE = "{http://www.w3.org/2001/XInclude}"
|
63 |
+
|
64 |
+
XINCLUDE_INCLUDE = XINCLUDE + "include"
|
65 |
+
XINCLUDE_FALLBACK = XINCLUDE + "fallback"
|
66 |
+
XINCLUDE_ITER_TAG = XINCLUDE + "*"
|
67 |
+
|
68 |
+
# For security reasons, the inclusion depth is limited to this read-only value by default.
|
69 |
+
DEFAULT_MAX_INCLUSION_DEPTH = 6
|
70 |
+
|
71 |
+
|
72 |
+
##
|
73 |
+
# Fatal include error.
|
74 |
+
|
75 |
+
class FatalIncludeError(etree.LxmlSyntaxError):
|
76 |
+
pass
|
77 |
+
|
78 |
+
|
79 |
+
class LimitedRecursiveIncludeError(FatalIncludeError):
|
80 |
+
pass
|
81 |
+
|
82 |
+
|
83 |
+
##
|
84 |
+
# ET compatible default loader.
|
85 |
+
# This loader reads an included resource from disk.
|
86 |
+
#
|
87 |
+
# @param href Resource reference.
|
88 |
+
# @param parse Parse mode. Either "xml" or "text".
|
89 |
+
# @param encoding Optional text encoding.
|
90 |
+
# @return The expanded resource. If the parse mode is "xml", this
|
91 |
+
# is an ElementTree instance. If the parse mode is "text", this
|
92 |
+
# is a Unicode string. If the loader fails, it can return None
|
93 |
+
# or raise an IOError exception.
|
94 |
+
# @throws IOError If the loader fails to load the resource.
|
95 |
+
|
96 |
+
def default_loader(href, parse, encoding=None):
|
97 |
+
file = open(href, 'rb')
|
98 |
+
if parse == "xml":
|
99 |
+
data = etree.parse(file).getroot()
|
100 |
+
else:
|
101 |
+
data = file.read()
|
102 |
+
if not encoding:
|
103 |
+
encoding = 'utf-8'
|
104 |
+
data = data.decode(encoding)
|
105 |
+
file.close()
|
106 |
+
return data
|
107 |
+
|
108 |
+
|
109 |
+
##
|
110 |
+
# Default loader used by lxml.etree - handles custom resolvers properly
|
111 |
+
#
|
112 |
+
|
113 |
+
def _lxml_default_loader(href, parse, encoding=None, parser=None):
|
114 |
+
if parse == "xml":
|
115 |
+
data = etree.parse(href, parser).getroot()
|
116 |
+
else:
|
117 |
+
if "://" in href:
|
118 |
+
f = urlopen(href)
|
119 |
+
else:
|
120 |
+
f = open(href, 'rb')
|
121 |
+
data = f.read()
|
122 |
+
f.close()
|
123 |
+
if not encoding:
|
124 |
+
encoding = 'utf-8'
|
125 |
+
data = data.decode(encoding)
|
126 |
+
return data
|
127 |
+
|
128 |
+
|
129 |
+
##
|
130 |
+
# Wrapper for ET compatibility - drops the parser
|
131 |
+
|
132 |
+
def _wrap_et_loader(loader):
|
133 |
+
def load(href, parse, encoding=None, parser=None):
|
134 |
+
return loader(href, parse, encoding)
|
135 |
+
return load
|
136 |
+
|
137 |
+
|
138 |
+
##
|
139 |
+
# Expand XInclude directives.
|
140 |
+
#
|
141 |
+
# @param elem Root element.
|
142 |
+
# @param loader Optional resource loader. If omitted, it defaults
|
143 |
+
# to {@link default_loader}. If given, it should be a callable
|
144 |
+
# that implements the same interface as <b>default_loader</b>.
|
145 |
+
# @param base_url The base URL of the original file, to resolve
|
146 |
+
# relative include file references.
|
147 |
+
# @param max_depth The maximum number of recursive inclusions.
|
148 |
+
# Limited to reduce the risk of malicious content explosion.
|
149 |
+
# Pass None to disable the limitation.
|
150 |
+
# @throws LimitedRecursiveIncludeError If the {@link max_depth} was exceeded.
|
151 |
+
# @throws FatalIncludeError If the function fails to include a given
|
152 |
+
# resource, or if the tree contains malformed XInclude elements.
|
153 |
+
# @throws IOError If the function fails to load a given resource.
|
154 |
+
# @returns the node or its replacement if it was an XInclude node
|
155 |
+
|
156 |
+
def include(elem, loader=None, base_url=None,
|
157 |
+
max_depth=DEFAULT_MAX_INCLUSION_DEPTH):
|
158 |
+
if max_depth is None:
|
159 |
+
max_depth = -1
|
160 |
+
elif max_depth < 0:
|
161 |
+
raise ValueError("expected non-negative depth or None for 'max_depth', got %r" % max_depth)
|
162 |
+
|
163 |
+
if base_url is None:
|
164 |
+
if hasattr(elem, 'getroot'):
|
165 |
+
tree = elem
|
166 |
+
elem = elem.getroot()
|
167 |
+
else:
|
168 |
+
tree = elem.getroottree()
|
169 |
+
if hasattr(tree, 'docinfo'):
|
170 |
+
base_url = tree.docinfo.URL
|
171 |
+
elif hasattr(elem, 'getroot'):
|
172 |
+
elem = elem.getroot()
|
173 |
+
_include(elem, loader, base_url, max_depth)
|
174 |
+
|
175 |
+
|
176 |
+
def _include(elem, loader=None, base_url=None,
|
177 |
+
max_depth=DEFAULT_MAX_INCLUSION_DEPTH, _parent_hrefs=None):
|
178 |
+
if loader is not None:
|
179 |
+
load_include = _wrap_et_loader(loader)
|
180 |
+
else:
|
181 |
+
load_include = _lxml_default_loader
|
182 |
+
|
183 |
+
if _parent_hrefs is None:
|
184 |
+
_parent_hrefs = set()
|
185 |
+
|
186 |
+
parser = elem.getroottree().parser
|
187 |
+
|
188 |
+
include_elements = list(
|
189 |
+
elem.iter(XINCLUDE_ITER_TAG))
|
190 |
+
|
191 |
+
for e in include_elements:
|
192 |
+
if e.tag == XINCLUDE_INCLUDE:
|
193 |
+
# process xinclude directive
|
194 |
+
href = urljoin(base_url, e.get("href"))
|
195 |
+
parse = e.get("parse", "xml")
|
196 |
+
parent = e.getparent()
|
197 |
+
if parse == "xml":
|
198 |
+
if href in _parent_hrefs:
|
199 |
+
raise FatalIncludeError(
|
200 |
+
"recursive include of %r detected" % href
|
201 |
+
)
|
202 |
+
if max_depth == 0:
|
203 |
+
raise LimitedRecursiveIncludeError(
|
204 |
+
"maximum xinclude depth reached when including file %s" % href)
|
205 |
+
node = load_include(href, parse, parser=parser)
|
206 |
+
if node is None:
|
207 |
+
raise FatalIncludeError(
|
208 |
+
"cannot load %r as %r" % (href, parse)
|
209 |
+
)
|
210 |
+
node = _include(node, loader, href, max_depth - 1, {href} | _parent_hrefs)
|
211 |
+
if e.tail:
|
212 |
+
node.tail = (node.tail or "") + e.tail
|
213 |
+
if parent is None:
|
214 |
+
return node # replaced the root node!
|
215 |
+
parent.replace(e, node)
|
216 |
+
elif parse == "text":
|
217 |
+
text = load_include(href, parse, encoding=e.get("encoding"))
|
218 |
+
if text is None:
|
219 |
+
raise FatalIncludeError(
|
220 |
+
"cannot load %r as %r" % (href, parse)
|
221 |
+
)
|
222 |
+
predecessor = e.getprevious()
|
223 |
+
if predecessor is not None:
|
224 |
+
predecessor.tail = (predecessor.tail or "") + text
|
225 |
+
elif parent is None:
|
226 |
+
return text # replaced the root node!
|
227 |
+
else:
|
228 |
+
parent.text = (parent.text or "") + text + (e.tail or "")
|
229 |
+
parent.remove(e)
|
230 |
+
else:
|
231 |
+
raise FatalIncludeError(
|
232 |
+
"unknown parse type in xi:include tag (%r)" % parse
|
233 |
+
)
|
234 |
+
elif e.tag == XINCLUDE_FALLBACK:
|
235 |
+
parent = e.getparent()
|
236 |
+
if parent is not None and parent.tag != XINCLUDE_INCLUDE:
|
237 |
+
raise FatalIncludeError(
|
238 |
+
"xi:fallback tag must be child of xi:include (%r)" % e.tag
|
239 |
+
)
|
240 |
+
else:
|
241 |
+
raise FatalIncludeError(
|
242 |
+
"Invalid element found in XInclude namespace (%r)" % e.tag
|
243 |
+
)
|
244 |
+
return elem
|
llmeval-env/lib/python3.10/site-packages/lxml/__init__.py
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# this is a package
|
2 |
+
|
3 |
+
__version__ = "5.2.1"
|
4 |
+
|
5 |
+
|
6 |
+
def get_include():
|
7 |
+
"""
|
8 |
+
Returns a list of header include paths (for lxml itself, libxml2
|
9 |
+
and libxslt) needed to compile C code against lxml if it was built
|
10 |
+
with statically linked libraries.
|
11 |
+
"""
|
12 |
+
import os
|
13 |
+
lxml_path = __path__[0]
|
14 |
+
include_path = os.path.join(lxml_path, 'includes')
|
15 |
+
includes = [include_path, lxml_path]
|
16 |
+
|
17 |
+
for name in os.listdir(include_path):
|
18 |
+
path = os.path.join(include_path, name)
|
19 |
+
if os.path.isdir(path):
|
20 |
+
includes.append(path)
|
21 |
+
|
22 |
+
return includes
|
llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/ElementInclude.cpython-310.pyc
ADDED
Binary file (3.81 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (702 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/_elementpath.cpython-310.pyc
ADDED
Binary file (6.39 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/builder.cpython-310.pyc
ADDED
Binary file (5.89 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/cssselect.cpython-310.pyc
ADDED
Binary file (3.59 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/doctestcompare.cpython-310.pyc
ADDED
Binary file (13.7 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/pyclasslookup.cpython-310.pyc
ADDED
Binary file (241 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/sax.cpython-310.pyc
ADDED
Binary file (8.14 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/usedoctest.cpython-310.pyc
ADDED
Binary file (431 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/lxml/builder.cpython-310-x86_64-linux-gnu.so
ADDED
Binary file (112 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/lxml/builder.py
ADDED
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# cython: language_level=2
|
2 |
+
|
3 |
+
#
|
4 |
+
# Element generator factory by Fredrik Lundh.
|
5 |
+
#
|
6 |
+
# Source:
|
7 |
+
# http://online.effbot.org/2006_11_01_archive.htm#et-builder
|
8 |
+
# http://effbot.python-hosting.com/file/stuff/sandbox/elementlib/builder.py
|
9 |
+
#
|
10 |
+
# --------------------------------------------------------------------
|
11 |
+
# The ElementTree toolkit is
|
12 |
+
#
|
13 |
+
# Copyright (c) 1999-2004 by Fredrik Lundh
|
14 |
+
#
|
15 |
+
# By obtaining, using, and/or copying this software and/or its
|
16 |
+
# associated documentation, you agree that you have read, understood,
|
17 |
+
# and will comply with the following terms and conditions:
|
18 |
+
#
|
19 |
+
# Permission to use, copy, modify, and distribute this software and
|
20 |
+
# its associated documentation for any purpose and without fee is
|
21 |
+
# hereby granted, provided that the above copyright notice appears in
|
22 |
+
# all copies, and that both that copyright notice and this permission
|
23 |
+
# notice appear in supporting documentation, and that the name of
|
24 |
+
# Secret Labs AB or the author not be used in advertising or publicity
|
25 |
+
# pertaining to distribution of the software without specific, written
|
26 |
+
# prior permission.
|
27 |
+
#
|
28 |
+
# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
|
29 |
+
# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
|
30 |
+
# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
|
31 |
+
# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
|
32 |
+
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
|
33 |
+
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
|
34 |
+
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
|
35 |
+
# OF THIS SOFTWARE.
|
36 |
+
# --------------------------------------------------------------------
|
37 |
+
|
38 |
+
"""
|
39 |
+
The ``E`` Element factory for generating XML documents.
|
40 |
+
"""
|
41 |
+
|
42 |
+
|
43 |
+
import lxml.etree as ET
|
44 |
+
_QName = ET.QName
|
45 |
+
|
46 |
+
from functools import partial
|
47 |
+
|
48 |
+
try:
|
49 |
+
basestring
|
50 |
+
except NameError:
|
51 |
+
basestring = str
|
52 |
+
|
53 |
+
try:
|
54 |
+
unicode
|
55 |
+
except NameError:
|
56 |
+
unicode = str
|
57 |
+
|
58 |
+
|
59 |
+
class ElementMaker:
|
60 |
+
"""Element generator factory.
|
61 |
+
|
62 |
+
Unlike the ordinary Element factory, the E factory allows you to pass in
|
63 |
+
more than just a tag and some optional attributes; you can also pass in
|
64 |
+
text and other elements. The text is added as either text or tail
|
65 |
+
attributes, and elements are inserted at the right spot. Some small
|
66 |
+
examples::
|
67 |
+
|
68 |
+
>>> from lxml import etree as ET
|
69 |
+
>>> from lxml.builder import E
|
70 |
+
|
71 |
+
>>> ET.tostring(E("tag"))
|
72 |
+
'<tag/>'
|
73 |
+
>>> ET.tostring(E("tag", "text"))
|
74 |
+
'<tag>text</tag>'
|
75 |
+
>>> ET.tostring(E("tag", "text", key="value"))
|
76 |
+
'<tag key="value">text</tag>'
|
77 |
+
>>> ET.tostring(E("tag", E("subtag", "text"), "tail"))
|
78 |
+
'<tag><subtag>text</subtag>tail</tag>'
|
79 |
+
|
80 |
+
For simple tags, the factory also allows you to write ``E.tag(...)`` instead
|
81 |
+
of ``E('tag', ...)``::
|
82 |
+
|
83 |
+
>>> ET.tostring(E.tag())
|
84 |
+
'<tag/>'
|
85 |
+
>>> ET.tostring(E.tag("text"))
|
86 |
+
'<tag>text</tag>'
|
87 |
+
>>> ET.tostring(E.tag(E.subtag("text"), "tail"))
|
88 |
+
'<tag><subtag>text</subtag>tail</tag>'
|
89 |
+
|
90 |
+
Here's a somewhat larger example; this shows how to generate HTML
|
91 |
+
documents, using a mix of prepared factory functions for inline elements,
|
92 |
+
nested ``E.tag`` calls, and embedded XHTML fragments::
|
93 |
+
|
94 |
+
# some common inline elements
|
95 |
+
A = E.a
|
96 |
+
I = E.i
|
97 |
+
B = E.b
|
98 |
+
|
99 |
+
def CLASS(v):
|
100 |
+
# helper function, 'class' is a reserved word
|
101 |
+
return {'class': v}
|
102 |
+
|
103 |
+
page = (
|
104 |
+
E.html(
|
105 |
+
E.head(
|
106 |
+
E.title("This is a sample document")
|
107 |
+
),
|
108 |
+
E.body(
|
109 |
+
E.h1("Hello!", CLASS("title")),
|
110 |
+
E.p("This is a paragraph with ", B("bold"), " text in it!"),
|
111 |
+
E.p("This is another paragraph, with a ",
|
112 |
+
A("link", href="http://www.python.org"), "."),
|
113 |
+
E.p("Here are some reserved characters: <spam&egg>."),
|
114 |
+
ET.XML("<p>And finally, here is an embedded XHTML fragment.</p>"),
|
115 |
+
)
|
116 |
+
)
|
117 |
+
)
|
118 |
+
|
119 |
+
print ET.tostring(page)
|
120 |
+
|
121 |
+
Here's a prettyprinted version of the output from the above script::
|
122 |
+
|
123 |
+
<html>
|
124 |
+
<head>
|
125 |
+
<title>This is a sample document</title>
|
126 |
+
</head>
|
127 |
+
<body>
|
128 |
+
<h1 class="title">Hello!</h1>
|
129 |
+
<p>This is a paragraph with <b>bold</b> text in it!</p>
|
130 |
+
<p>This is another paragraph, with <a href="http://www.python.org">link</a>.</p>
|
131 |
+
<p>Here are some reserved characters: <spam&egg>.</p>
|
132 |
+
<p>And finally, here is an embedded XHTML fragment.</p>
|
133 |
+
</body>
|
134 |
+
</html>
|
135 |
+
|
136 |
+
For namespace support, you can pass a namespace map (``nsmap``)
|
137 |
+
and/or a specific target ``namespace`` to the ElementMaker class::
|
138 |
+
|
139 |
+
>>> E = ElementMaker(namespace="http://my.ns/")
|
140 |
+
>>> print(ET.tostring( E.test ))
|
141 |
+
<test xmlns="http://my.ns/"/>
|
142 |
+
|
143 |
+
>>> E = ElementMaker(namespace="http://my.ns/", nsmap={'p':'http://my.ns/'})
|
144 |
+
>>> print(ET.tostring( E.test ))
|
145 |
+
<p:test xmlns:p="http://my.ns/"/>
|
146 |
+
"""
|
147 |
+
|
148 |
+
def __init__(self, typemap=None,
|
149 |
+
namespace=None, nsmap=None, makeelement=None):
|
150 |
+
self._namespace = '{' + namespace + '}' if namespace is not None else None
|
151 |
+
self._nsmap = dict(nsmap) if nsmap else None
|
152 |
+
|
153 |
+
assert makeelement is None or callable(makeelement)
|
154 |
+
self._makeelement = makeelement if makeelement is not None else ET.Element
|
155 |
+
|
156 |
+
# initialize the default type map functions for this element factory
|
157 |
+
typemap = dict(typemap) if typemap else {}
|
158 |
+
|
159 |
+
def add_text(elem, item):
|
160 |
+
try:
|
161 |
+
last_child = elem[-1]
|
162 |
+
except IndexError:
|
163 |
+
elem.text = (elem.text or "") + item
|
164 |
+
else:
|
165 |
+
last_child.tail = (last_child.tail or "") + item
|
166 |
+
|
167 |
+
def add_cdata(elem, cdata):
|
168 |
+
if elem.text:
|
169 |
+
raise ValueError("Can't add a CDATA section. Element already has some text: %r" % elem.text)
|
170 |
+
elem.text = cdata
|
171 |
+
|
172 |
+
if str not in typemap:
|
173 |
+
typemap[str] = add_text
|
174 |
+
if unicode not in typemap:
|
175 |
+
typemap[unicode] = add_text
|
176 |
+
if ET.CDATA not in typemap:
|
177 |
+
typemap[ET.CDATA] = add_cdata
|
178 |
+
|
179 |
+
def add_dict(elem, item):
|
180 |
+
attrib = elem.attrib
|
181 |
+
for k, v in item.items():
|
182 |
+
if isinstance(v, basestring):
|
183 |
+
attrib[k] = v
|
184 |
+
else:
|
185 |
+
attrib[k] = typemap[type(v)](None, v)
|
186 |
+
|
187 |
+
if dict not in typemap:
|
188 |
+
typemap[dict] = add_dict
|
189 |
+
|
190 |
+
self._typemap = typemap
|
191 |
+
|
192 |
+
def __call__(self, tag, *children, **attrib):
|
193 |
+
typemap = self._typemap
|
194 |
+
|
195 |
+
# We'll usually get a 'str', and the compiled type check is very fast.
|
196 |
+
if not isinstance(tag, str) and isinstance(tag, _QName):
|
197 |
+
# A QName is explicitly qualified, do not look at self._namespace.
|
198 |
+
tag = tag.text
|
199 |
+
elif self._namespace is not None and tag[0] != '{':
|
200 |
+
tag = self._namespace + tag
|
201 |
+
elem = self._makeelement(tag, nsmap=self._nsmap)
|
202 |
+
if attrib:
|
203 |
+
typemap[dict](elem, attrib)
|
204 |
+
|
205 |
+
for item in children:
|
206 |
+
if callable(item):
|
207 |
+
item = item()
|
208 |
+
t = typemap.get(type(item))
|
209 |
+
if t is None:
|
210 |
+
if ET.iselement(item):
|
211 |
+
elem.append(item)
|
212 |
+
continue
|
213 |
+
for basetype in type(item).__mro__:
|
214 |
+
# See if the typemap knows of any of this type's bases.
|
215 |
+
t = typemap.get(basetype)
|
216 |
+
if t is not None:
|
217 |
+
break
|
218 |
+
else:
|
219 |
+
raise TypeError("bad argument type: %s(%r)" %
|
220 |
+
(type(item).__name__, item))
|
221 |
+
v = t(elem, item)
|
222 |
+
if v:
|
223 |
+
typemap.get(type(v))(elem, v)
|
224 |
+
|
225 |
+
return elem
|
226 |
+
|
227 |
+
def __getattr__(self, tag):
|
228 |
+
return partial(self, tag)
|
229 |
+
|
230 |
+
|
231 |
+
# create factory object
|
232 |
+
E = ElementMaker()
|
llmeval-env/lib/python3.10/site-packages/lxml/cleanup.pxi
ADDED
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# functions for tree cleanup and removing elements from subtrees
|
2 |
+
|
3 |
+
def cleanup_namespaces(tree_or_element, top_nsmap=None, keep_ns_prefixes=None):
|
4 |
+
"""cleanup_namespaces(tree_or_element, top_nsmap=None, keep_ns_prefixes=None)
|
5 |
+
|
6 |
+
Remove all namespace declarations from a subtree that are not used
|
7 |
+
by any of the elements or attributes in that tree.
|
8 |
+
|
9 |
+
If a 'top_nsmap' is provided, it must be a mapping from prefixes
|
10 |
+
to namespace URIs. These namespaces will be declared on the top
|
11 |
+
element of the subtree before running the cleanup, which allows
|
12 |
+
moving namespace declarations to the top of the tree.
|
13 |
+
|
14 |
+
If a 'keep_ns_prefixes' is provided, it must be a list of prefixes.
|
15 |
+
These prefixes will not be removed as part of the cleanup.
|
16 |
+
"""
|
17 |
+
element = _rootNodeOrRaise(tree_or_element)
|
18 |
+
c_element = element._c_node
|
19 |
+
|
20 |
+
if top_nsmap:
|
21 |
+
doc = element._doc
|
22 |
+
# declare namespaces from nsmap, then apply them to the subtree
|
23 |
+
_setNodeNamespaces(c_element, doc, None, top_nsmap)
|
24 |
+
moveNodeToDocument(doc, c_element.doc, c_element)
|
25 |
+
|
26 |
+
keep_ns_prefixes = (
|
27 |
+
set([_utf8(prefix) for prefix in keep_ns_prefixes])
|
28 |
+
if keep_ns_prefixes else None)
|
29 |
+
|
30 |
+
_removeUnusedNamespaceDeclarations(c_element, keep_ns_prefixes)
|
31 |
+
|
32 |
+
|
33 |
+
def strip_attributes(tree_or_element, *attribute_names):
|
34 |
+
"""strip_attributes(tree_or_element, *attribute_names)
|
35 |
+
|
36 |
+
Delete all attributes with the provided attribute names from an
|
37 |
+
Element (or ElementTree) and its descendants.
|
38 |
+
|
39 |
+
Attribute names can contain wildcards as in `_Element.iter`.
|
40 |
+
|
41 |
+
Example usage::
|
42 |
+
|
43 |
+
strip_attributes(root_element,
|
44 |
+
'simpleattr',
|
45 |
+
'{http://some/ns}attrname',
|
46 |
+
'{http://other/ns}*')
|
47 |
+
"""
|
48 |
+
cdef _MultiTagMatcher matcher
|
49 |
+
element = _rootNodeOrRaise(tree_or_element)
|
50 |
+
if not attribute_names:
|
51 |
+
return
|
52 |
+
|
53 |
+
matcher = _MultiTagMatcher.__new__(_MultiTagMatcher, attribute_names)
|
54 |
+
matcher.cacheTags(element._doc)
|
55 |
+
if matcher.rejectsAllAttributes():
|
56 |
+
return
|
57 |
+
_strip_attributes(element._c_node, matcher)
|
58 |
+
|
59 |
+
|
60 |
+
cdef _strip_attributes(xmlNode* c_node, _MultiTagMatcher matcher):
|
61 |
+
cdef xmlAttr* c_attr
|
62 |
+
cdef xmlAttr* c_next_attr
|
63 |
+
tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_node, c_node, 1)
|
64 |
+
if c_node.type == tree.XML_ELEMENT_NODE:
|
65 |
+
c_attr = c_node.properties
|
66 |
+
while c_attr is not NULL:
|
67 |
+
c_next_attr = c_attr.next
|
68 |
+
if matcher.matchesAttribute(c_attr):
|
69 |
+
tree.xmlRemoveProp(c_attr)
|
70 |
+
c_attr = c_next_attr
|
71 |
+
tree.END_FOR_EACH_ELEMENT_FROM(c_node)
|
72 |
+
|
73 |
+
|
74 |
+
def strip_elements(tree_or_element, *tag_names, bint with_tail=True):
|
75 |
+
"""strip_elements(tree_or_element, *tag_names, with_tail=True)
|
76 |
+
|
77 |
+
Delete all elements with the provided tag names from a tree or
|
78 |
+
subtree. This will remove the elements and their entire subtree,
|
79 |
+
including all their attributes, text content and descendants. It
|
80 |
+
will also remove the tail text of the element unless you
|
81 |
+
explicitly set the ``with_tail`` keyword argument option to False.
|
82 |
+
|
83 |
+
Tag names can contain wildcards as in `_Element.iter`.
|
84 |
+
|
85 |
+
Note that this will not delete the element (or ElementTree root
|
86 |
+
element) that you passed even if it matches. It will only treat
|
87 |
+
its descendants. If you want to include the root element, check
|
88 |
+
its tag name directly before even calling this function.
|
89 |
+
|
90 |
+
Example usage::
|
91 |
+
|
92 |
+
strip_elements(some_element,
|
93 |
+
'simpletagname', # non-namespaced tag
|
94 |
+
'{http://some/ns}tagname', # namespaced tag
|
95 |
+
'{http://some/other/ns}*' # any tag from a namespace
|
96 |
+
lxml.etree.Comment # comments
|
97 |
+
)
|
98 |
+
"""
|
99 |
+
cdef _MultiTagMatcher matcher
|
100 |
+
doc = _documentOrRaise(tree_or_element)
|
101 |
+
element = _rootNodeOrRaise(tree_or_element)
|
102 |
+
if not tag_names:
|
103 |
+
return
|
104 |
+
|
105 |
+
matcher = _MultiTagMatcher.__new__(_MultiTagMatcher, tag_names)
|
106 |
+
matcher.cacheTags(doc)
|
107 |
+
if matcher.rejectsAll():
|
108 |
+
return
|
109 |
+
|
110 |
+
if isinstance(tree_or_element, _ElementTree):
|
111 |
+
# include PIs and comments next to the root node
|
112 |
+
if matcher.matchesType(tree.XML_COMMENT_NODE):
|
113 |
+
_removeSiblings(element._c_node, tree.XML_COMMENT_NODE, with_tail)
|
114 |
+
if matcher.matchesType(tree.XML_PI_NODE):
|
115 |
+
_removeSiblings(element._c_node, tree.XML_PI_NODE, with_tail)
|
116 |
+
_strip_elements(doc, element._c_node, matcher, with_tail)
|
117 |
+
|
118 |
+
cdef _strip_elements(_Document doc, xmlNode* c_node, _MultiTagMatcher matcher,
|
119 |
+
bint with_tail):
|
120 |
+
cdef xmlNode* c_child
|
121 |
+
cdef xmlNode* c_next
|
122 |
+
|
123 |
+
tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_node, c_node, 1)
|
124 |
+
if c_node.type == tree.XML_ELEMENT_NODE:
|
125 |
+
# we run through the children here to prevent any problems
|
126 |
+
# with the tree iteration which would occur if we unlinked the
|
127 |
+
# c_node itself
|
128 |
+
c_child = _findChildForwards(c_node, 0)
|
129 |
+
while c_child is not NULL:
|
130 |
+
c_next = _nextElement(c_child)
|
131 |
+
if matcher.matches(c_child):
|
132 |
+
if c_child.type == tree.XML_ELEMENT_NODE:
|
133 |
+
if not with_tail:
|
134 |
+
tree.xmlUnlinkNode(c_child)
|
135 |
+
_removeNode(doc, c_child)
|
136 |
+
else:
|
137 |
+
if with_tail:
|
138 |
+
_removeText(c_child.next)
|
139 |
+
tree.xmlUnlinkNode(c_child)
|
140 |
+
attemptDeallocation(c_child)
|
141 |
+
c_child = c_next
|
142 |
+
tree.END_FOR_EACH_ELEMENT_FROM(c_node)
|
143 |
+
|
144 |
+
|
145 |
+
def strip_tags(tree_or_element, *tag_names):
|
146 |
+
"""strip_tags(tree_or_element, *tag_names)
|
147 |
+
|
148 |
+
Delete all elements with the provided tag names from a tree or
|
149 |
+
subtree. This will remove the elements and their attributes, but
|
150 |
+
*not* their text/tail content or descendants. Instead, it will
|
151 |
+
merge the text content and children of the element into its
|
152 |
+
parent.
|
153 |
+
|
154 |
+
Tag names can contain wildcards as in `_Element.iter`.
|
155 |
+
|
156 |
+
Note that this will not delete the element (or ElementTree root
|
157 |
+
element) that you passed even if it matches. It will only treat
|
158 |
+
its descendants.
|
159 |
+
|
160 |
+
Example usage::
|
161 |
+
|
162 |
+
strip_tags(some_element,
|
163 |
+
'simpletagname', # non-namespaced tag
|
164 |
+
'{http://some/ns}tagname', # namespaced tag
|
165 |
+
'{http://some/other/ns}*' # any tag from a namespace
|
166 |
+
Comment # comments (including their text!)
|
167 |
+
)
|
168 |
+
"""
|
169 |
+
cdef _MultiTagMatcher matcher
|
170 |
+
doc = _documentOrRaise(tree_or_element)
|
171 |
+
element = _rootNodeOrRaise(tree_or_element)
|
172 |
+
if not tag_names:
|
173 |
+
return
|
174 |
+
|
175 |
+
matcher = _MultiTagMatcher.__new__(_MultiTagMatcher, tag_names)
|
176 |
+
matcher.cacheTags(doc)
|
177 |
+
if matcher.rejectsAll():
|
178 |
+
return
|
179 |
+
|
180 |
+
if isinstance(tree_or_element, _ElementTree):
|
181 |
+
# include PIs and comments next to the root node
|
182 |
+
if matcher.matchesType(tree.XML_COMMENT_NODE):
|
183 |
+
_removeSiblings(element._c_node, tree.XML_COMMENT_NODE, 0)
|
184 |
+
if matcher.matchesType(tree.XML_PI_NODE):
|
185 |
+
_removeSiblings(element._c_node, tree.XML_PI_NODE, 0)
|
186 |
+
_strip_tags(doc, element._c_node, matcher)
|
187 |
+
|
188 |
+
cdef _strip_tags(_Document doc, xmlNode* c_node, _MultiTagMatcher matcher):
|
189 |
+
cdef xmlNode* c_child
|
190 |
+
cdef xmlNode* c_next
|
191 |
+
|
192 |
+
tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_node, c_node, 1)
|
193 |
+
if c_node.type == tree.XML_ELEMENT_NODE:
|
194 |
+
# we run through the children here to prevent any problems
|
195 |
+
# with the tree iteration which would occur if we unlinked the
|
196 |
+
# c_node itself
|
197 |
+
c_child = _findChildForwards(c_node, 0)
|
198 |
+
while c_child is not NULL:
|
199 |
+
if not matcher.matches(c_child):
|
200 |
+
c_child = _nextElement(c_child)
|
201 |
+
continue
|
202 |
+
if c_child.type == tree.XML_ELEMENT_NODE:
|
203 |
+
c_next = _findChildForwards(c_child, 0) or _nextElement(c_child)
|
204 |
+
_replaceNodeByChildren(doc, c_child)
|
205 |
+
if not attemptDeallocation(c_child):
|
206 |
+
if c_child.nsDef is not NULL:
|
207 |
+
# make namespaces absolute
|
208 |
+
moveNodeToDocument(doc, doc._c_doc, c_child)
|
209 |
+
c_child = c_next
|
210 |
+
else:
|
211 |
+
c_next = _nextElement(c_child)
|
212 |
+
tree.xmlUnlinkNode(c_child)
|
213 |
+
attemptDeallocation(c_child)
|
214 |
+
c_child = c_next
|
215 |
+
tree.END_FOR_EACH_ELEMENT_FROM(c_node)
|
llmeval-env/lib/python3.10/site-packages/lxml/debug.pxi
ADDED
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
@cython.final
|
2 |
+
@cython.internal
|
3 |
+
cdef class _MemDebug:
|
4 |
+
"""Debugging support for the memory allocation in libxml2.
|
5 |
+
"""
|
6 |
+
def bytes_used(self):
|
7 |
+
"""bytes_used(self)
|
8 |
+
|
9 |
+
Returns the total amount of memory (in bytes) currently used by libxml2.
|
10 |
+
Note that libxml2 constrains this value to a C int, which limits
|
11 |
+
the accuracy on 64 bit systems.
|
12 |
+
"""
|
13 |
+
return tree.xmlMemUsed()
|
14 |
+
|
15 |
+
def blocks_used(self):
|
16 |
+
"""blocks_used(self)
|
17 |
+
|
18 |
+
Returns the total number of memory blocks currently allocated by libxml2.
|
19 |
+
Note that libxml2 constrains this value to a C int, which limits
|
20 |
+
the accuracy on 64 bit systems.
|
21 |
+
"""
|
22 |
+
return tree.xmlMemBlocks()
|
23 |
+
|
24 |
+
def dict_size(self):
|
25 |
+
"""dict_size(self)
|
26 |
+
|
27 |
+
Returns the current size of the global name dictionary used by libxml2
|
28 |
+
for the current thread. Each thread has its own dictionary.
|
29 |
+
"""
|
30 |
+
c_dict = __GLOBAL_PARSER_CONTEXT._getThreadDict(NULL)
|
31 |
+
if c_dict is NULL:
|
32 |
+
raise MemoryError()
|
33 |
+
return tree.xmlDictSize(c_dict)
|
34 |
+
|
35 |
+
def dump(self, output_file=None, byte_count=None):
|
36 |
+
"""dump(self, output_file=None, byte_count=None)
|
37 |
+
|
38 |
+
Dumps the current memory blocks allocated by libxml2 to a file.
|
39 |
+
|
40 |
+
The optional parameter 'output_file' specifies the file path. It defaults
|
41 |
+
to the file ".memorylist" in the current directory.
|
42 |
+
|
43 |
+
The optional parameter 'byte_count' limits the number of bytes in the dump.
|
44 |
+
Note that this parameter is ignored when lxml is compiled against a libxml2
|
45 |
+
version before 2.7.0.
|
46 |
+
"""
|
47 |
+
cdef Py_ssize_t c_count
|
48 |
+
if output_file is None:
|
49 |
+
output_file = b'.memorylist'
|
50 |
+
elif isinstance(output_file, unicode):
|
51 |
+
output_file.encode(sys.getfilesystemencoding())
|
52 |
+
|
53 |
+
f = stdio.fopen(output_file, "w")
|
54 |
+
if f is NULL:
|
55 |
+
raise IOError(f"Failed to create file {output_file.decode(sys.getfilesystemencoding())}")
|
56 |
+
try:
|
57 |
+
if byte_count is None:
|
58 |
+
tree.xmlMemDisplay(f)
|
59 |
+
else:
|
60 |
+
c_count = byte_count
|
61 |
+
tree.xmlMemDisplayLast(f, c_count)
|
62 |
+
finally:
|
63 |
+
stdio.fclose(f)
|
64 |
+
|
65 |
+
def show(self, output_file=None, block_count=None):
|
66 |
+
"""show(self, output_file=None, block_count=None)
|
67 |
+
|
68 |
+
Dumps the current memory blocks allocated by libxml2 to a file.
|
69 |
+
The output file format is suitable for line diffing.
|
70 |
+
|
71 |
+
The optional parameter 'output_file' specifies the file path. It defaults
|
72 |
+
to the file ".memorydump" in the current directory.
|
73 |
+
|
74 |
+
The optional parameter 'block_count' limits the number of blocks
|
75 |
+
in the dump.
|
76 |
+
"""
|
77 |
+
if output_file is None:
|
78 |
+
output_file = b'.memorydump'
|
79 |
+
elif isinstance(output_file, unicode):
|
80 |
+
output_file.encode(sys.getfilesystemencoding())
|
81 |
+
|
82 |
+
f = stdio.fopen(output_file, "w")
|
83 |
+
if f is NULL:
|
84 |
+
raise IOError(f"Failed to create file {output_file.decode(sys.getfilesystemencoding())}")
|
85 |
+
try:
|
86 |
+
tree.xmlMemShow(f, block_count if block_count is not None else tree.xmlMemBlocks())
|
87 |
+
finally:
|
88 |
+
stdio.fclose(f)
|
89 |
+
|
90 |
+
memory_debugger = _MemDebug()
|
llmeval-env/lib/python3.10/site-packages/lxml/docloader.pxi
ADDED
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Custom resolver API
|
2 |
+
|
3 |
+
ctypedef enum _InputDocumentDataType:
|
4 |
+
PARSER_DATA_INVALID
|
5 |
+
PARSER_DATA_EMPTY
|
6 |
+
PARSER_DATA_STRING
|
7 |
+
PARSER_DATA_FILENAME
|
8 |
+
PARSER_DATA_FILE
|
9 |
+
|
10 |
+
@cython.final
|
11 |
+
@cython.internal
|
12 |
+
cdef class _InputDocument:
|
13 |
+
cdef _InputDocumentDataType _type
|
14 |
+
cdef bytes _data_bytes
|
15 |
+
cdef object _filename
|
16 |
+
cdef object _file
|
17 |
+
cdef bint _close_file
|
18 |
+
|
19 |
+
def __cinit__(self):
|
20 |
+
self._type = PARSER_DATA_INVALID
|
21 |
+
|
22 |
+
|
23 |
+
cdef class Resolver:
|
24 |
+
"This is the base class of all resolvers."
|
25 |
+
def resolve(self, system_url, public_id, context):
|
26 |
+
"""resolve(self, system_url, public_id, context)
|
27 |
+
|
28 |
+
Override this method to resolve an external source by
|
29 |
+
``system_url`` and ``public_id``. The third argument is an
|
30 |
+
opaque context object.
|
31 |
+
|
32 |
+
Return the result of one of the ``resolve_*()`` methods.
|
33 |
+
"""
|
34 |
+
return None
|
35 |
+
|
36 |
+
def resolve_empty(self, context):
|
37 |
+
"""resolve_empty(self, context)
|
38 |
+
|
39 |
+
Return an empty input document.
|
40 |
+
|
41 |
+
Pass context as parameter.
|
42 |
+
"""
|
43 |
+
cdef _InputDocument doc_ref
|
44 |
+
doc_ref = _InputDocument()
|
45 |
+
doc_ref._type = PARSER_DATA_EMPTY
|
46 |
+
return doc_ref
|
47 |
+
|
48 |
+
def resolve_string(self, string, context, *, base_url=None):
|
49 |
+
"""resolve_string(self, string, context, base_url=None)
|
50 |
+
|
51 |
+
Return a parsable string as input document.
|
52 |
+
|
53 |
+
Pass data string and context as parameters. You can pass the
|
54 |
+
source URL or filename through the ``base_url`` keyword
|
55 |
+
argument.
|
56 |
+
"""
|
57 |
+
cdef _InputDocument doc_ref
|
58 |
+
if isinstance(string, unicode):
|
59 |
+
string = (<unicode>string).encode('utf8')
|
60 |
+
elif not isinstance(string, bytes):
|
61 |
+
raise TypeError, "argument must be a byte string or unicode string"
|
62 |
+
doc_ref = _InputDocument()
|
63 |
+
doc_ref._type = PARSER_DATA_STRING
|
64 |
+
doc_ref._data_bytes = string
|
65 |
+
if base_url is not None:
|
66 |
+
doc_ref._filename = _encodeFilename(base_url)
|
67 |
+
return doc_ref
|
68 |
+
|
69 |
+
def resolve_filename(self, filename, context):
|
70 |
+
"""resolve_filename(self, filename, context)
|
71 |
+
|
72 |
+
Return the name of a parsable file as input document.
|
73 |
+
|
74 |
+
Pass filename and context as parameters. You can also pass a
|
75 |
+
URL with an HTTP, FTP or file target.
|
76 |
+
"""
|
77 |
+
cdef _InputDocument doc_ref
|
78 |
+
doc_ref = _InputDocument()
|
79 |
+
doc_ref._type = PARSER_DATA_FILENAME
|
80 |
+
doc_ref._filename = _encodeFilename(filename)
|
81 |
+
return doc_ref
|
82 |
+
|
83 |
+
def resolve_file(self, f, context, *, base_url=None, bint close=True):
|
84 |
+
"""resolve_file(self, f, context, base_url=None, close=True)
|
85 |
+
|
86 |
+
Return an open file-like object as input document.
|
87 |
+
|
88 |
+
Pass open file and context as parameters. You can pass the
|
89 |
+
base URL or filename of the file through the ``base_url``
|
90 |
+
keyword argument. If the ``close`` flag is True (the
|
91 |
+
default), the file will be closed after reading.
|
92 |
+
|
93 |
+
Note that using ``.resolve_filename()`` is more efficient,
|
94 |
+
especially in threaded environments.
|
95 |
+
"""
|
96 |
+
cdef _InputDocument doc_ref
|
97 |
+
try:
|
98 |
+
f.read
|
99 |
+
except AttributeError:
|
100 |
+
raise TypeError, "Argument is not a file-like object"
|
101 |
+
doc_ref = _InputDocument()
|
102 |
+
doc_ref._type = PARSER_DATA_FILE
|
103 |
+
if base_url is not None:
|
104 |
+
doc_ref._filename = _encodeFilename(base_url)
|
105 |
+
else:
|
106 |
+
doc_ref._filename = _getFilenameForFile(f)
|
107 |
+
doc_ref._close_file = close
|
108 |
+
doc_ref._file = f
|
109 |
+
return doc_ref
|
110 |
+
|
111 |
+
@cython.final
|
112 |
+
@cython.internal
|
113 |
+
cdef class _ResolverRegistry:
|
114 |
+
cdef object _resolvers
|
115 |
+
cdef Resolver _default_resolver
|
116 |
+
def __cinit__(self, Resolver default_resolver=None):
|
117 |
+
self._resolvers = set()
|
118 |
+
self._default_resolver = default_resolver
|
119 |
+
|
120 |
+
def add(self, Resolver resolver not None):
|
121 |
+
"""add(self, resolver)
|
122 |
+
|
123 |
+
Register a resolver.
|
124 |
+
|
125 |
+
For each requested entity, the 'resolve' method of the resolver will
|
126 |
+
be called and the result will be passed to the parser. If this method
|
127 |
+
returns None, the request will be delegated to other resolvers or the
|
128 |
+
default resolver. The resolvers will be tested in an arbitrary order
|
129 |
+
until the first match is found.
|
130 |
+
"""
|
131 |
+
self._resolvers.add(resolver)
|
132 |
+
|
133 |
+
def remove(self, resolver):
|
134 |
+
"remove(self, resolver)"
|
135 |
+
self._resolvers.discard(resolver)
|
136 |
+
|
137 |
+
cdef _ResolverRegistry _copy(self):
|
138 |
+
cdef _ResolverRegistry registry
|
139 |
+
registry = _ResolverRegistry(self._default_resolver)
|
140 |
+
registry._resolvers = self._resolvers.copy()
|
141 |
+
return registry
|
142 |
+
|
143 |
+
def copy(self):
|
144 |
+
"copy(self)"
|
145 |
+
return self._copy()
|
146 |
+
|
147 |
+
def resolve(self, system_url, public_id, context):
|
148 |
+
"resolve(self, system_url, public_id, context)"
|
149 |
+
for resolver in self._resolvers:
|
150 |
+
result = resolver.resolve(system_url, public_id, context)
|
151 |
+
if result is not None:
|
152 |
+
return result
|
153 |
+
if self._default_resolver is None:
|
154 |
+
return None
|
155 |
+
return self._default_resolver.resolve(system_url, public_id, context)
|
156 |
+
|
157 |
+
def __repr__(self):
|
158 |
+
return repr(self._resolvers)
|
159 |
+
|
160 |
+
|
161 |
+
@cython.internal
|
162 |
+
cdef class _ResolverContext(_ExceptionContext):
|
163 |
+
cdef _ResolverRegistry _resolvers
|
164 |
+
cdef _TempStore _storage
|
165 |
+
|
166 |
+
cdef int clear(self) except -1:
|
167 |
+
_ExceptionContext.clear(self)
|
168 |
+
self._storage.clear()
|
169 |
+
return 0
|
170 |
+
|
171 |
+
|
172 |
+
cdef _initResolverContext(_ResolverContext context,
|
173 |
+
_ResolverRegistry resolvers):
|
174 |
+
if resolvers is None:
|
175 |
+
context._resolvers = _ResolverRegistry()
|
176 |
+
else:
|
177 |
+
context._resolvers = resolvers
|
178 |
+
context._storage = _TempStore()
|
llmeval-env/lib/python3.10/site-packages/lxml/doctestcompare.py
ADDED
@@ -0,0 +1,488 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
lxml-based doctest output comparison.
|
3 |
+
|
4 |
+
Note: normally, you should just import the `lxml.usedoctest` and
|
5 |
+
`lxml.html.usedoctest` modules from within a doctest, instead of this
|
6 |
+
one::
|
7 |
+
|
8 |
+
>>> import lxml.usedoctest # for XML output
|
9 |
+
|
10 |
+
>>> import lxml.html.usedoctest # for HTML output
|
11 |
+
|
12 |
+
To use this module directly, you must call ``lxmldoctest.install()``,
|
13 |
+
which will cause doctest to use this in all subsequent calls.
|
14 |
+
|
15 |
+
This changes the way output is checked and comparisons are made for
|
16 |
+
XML or HTML-like content.
|
17 |
+
|
18 |
+
XML or HTML content is noticed because the example starts with ``<``
|
19 |
+
(it's HTML if it starts with ``<html``). You can also use the
|
20 |
+
``PARSE_HTML`` and ``PARSE_XML`` flags to force parsing.
|
21 |
+
|
22 |
+
Some rough wildcard-like things are allowed. Whitespace is generally
|
23 |
+
ignored (except in attributes). In text (attributes and text in the
|
24 |
+
body) you can use ``...`` as a wildcard. In an example it also
|
25 |
+
matches any trailing tags in the element, though it does not match
|
26 |
+
leading tags. You may create a tag ``<any>`` or include an ``any``
|
27 |
+
attribute in the tag. An ``any`` tag matches any tag, while the
|
28 |
+
attribute matches any and all attributes.
|
29 |
+
|
30 |
+
When a match fails, the reformatted example and gotten text is
|
31 |
+
displayed (indented), and a rough diff-like output is given. Anything
|
32 |
+
marked with ``+`` is in the output but wasn't supposed to be, and
|
33 |
+
similarly ``-`` means its in the example but wasn't in the output.
|
34 |
+
|
35 |
+
You can disable parsing on one line with ``# doctest:+NOPARSE_MARKUP``
|
36 |
+
"""
|
37 |
+
|
38 |
+
from lxml import etree
|
39 |
+
import sys
|
40 |
+
import re
|
41 |
+
import doctest
|
42 |
+
try:
|
43 |
+
from html import escape as html_escape
|
44 |
+
except ImportError:
|
45 |
+
from cgi import escape as html_escape
|
46 |
+
|
47 |
+
__all__ = ['PARSE_HTML', 'PARSE_XML', 'NOPARSE_MARKUP', 'LXMLOutputChecker',
|
48 |
+
'LHTMLOutputChecker', 'install', 'temp_install']
|
49 |
+
|
50 |
+
PARSE_HTML = doctest.register_optionflag('PARSE_HTML')
|
51 |
+
PARSE_XML = doctest.register_optionflag('PARSE_XML')
|
52 |
+
NOPARSE_MARKUP = doctest.register_optionflag('NOPARSE_MARKUP')
|
53 |
+
|
54 |
+
OutputChecker = doctest.OutputChecker
|
55 |
+
|
56 |
+
def strip(v):
|
57 |
+
if v is None:
|
58 |
+
return None
|
59 |
+
else:
|
60 |
+
return v.strip()
|
61 |
+
|
62 |
+
def norm_whitespace(v):
|
63 |
+
return _norm_whitespace_re.sub(' ', v)
|
64 |
+
|
65 |
+
_html_parser = etree.HTMLParser(recover=False, remove_blank_text=True)
|
66 |
+
|
67 |
+
def html_fromstring(html):
|
68 |
+
return etree.fromstring(html, _html_parser)
|
69 |
+
|
70 |
+
# We use this to distinguish repr()s from elements:
|
71 |
+
_repr_re = re.compile(r'^<[^>]+ (at|object) ')
|
72 |
+
_norm_whitespace_re = re.compile(r'[ \t\n][ \t\n]+')
|
73 |
+
|
74 |
+
class LXMLOutputChecker(OutputChecker):
|
75 |
+
|
76 |
+
empty_tags = (
|
77 |
+
'param', 'img', 'area', 'br', 'basefont', 'input',
|
78 |
+
'base', 'meta', 'link', 'col')
|
79 |
+
|
80 |
+
def get_default_parser(self):
|
81 |
+
return etree.XML
|
82 |
+
|
83 |
+
def check_output(self, want, got, optionflags):
|
84 |
+
alt_self = getattr(self, '_temp_override_self', None)
|
85 |
+
if alt_self is not None:
|
86 |
+
super_method = self._temp_call_super_check_output
|
87 |
+
self = alt_self
|
88 |
+
else:
|
89 |
+
super_method = OutputChecker.check_output
|
90 |
+
parser = self.get_parser(want, got, optionflags)
|
91 |
+
if not parser:
|
92 |
+
return super_method(
|
93 |
+
self, want, got, optionflags)
|
94 |
+
try:
|
95 |
+
want_doc = parser(want)
|
96 |
+
except etree.XMLSyntaxError:
|
97 |
+
return False
|
98 |
+
try:
|
99 |
+
got_doc = parser(got)
|
100 |
+
except etree.XMLSyntaxError:
|
101 |
+
return False
|
102 |
+
return self.compare_docs(want_doc, got_doc)
|
103 |
+
|
104 |
+
def get_parser(self, want, got, optionflags):
|
105 |
+
parser = None
|
106 |
+
if NOPARSE_MARKUP & optionflags:
|
107 |
+
return None
|
108 |
+
if PARSE_HTML & optionflags:
|
109 |
+
parser = html_fromstring
|
110 |
+
elif PARSE_XML & optionflags:
|
111 |
+
parser = etree.XML
|
112 |
+
elif (want.strip().lower().startswith('<html')
|
113 |
+
and got.strip().startswith('<html')):
|
114 |
+
parser = html_fromstring
|
115 |
+
elif (self._looks_like_markup(want)
|
116 |
+
and self._looks_like_markup(got)):
|
117 |
+
parser = self.get_default_parser()
|
118 |
+
return parser
|
119 |
+
|
120 |
+
def _looks_like_markup(self, s):
|
121 |
+
s = s.strip()
|
122 |
+
return (s.startswith('<')
|
123 |
+
and not _repr_re.search(s))
|
124 |
+
|
125 |
+
def compare_docs(self, want, got):
|
126 |
+
if not self.tag_compare(want.tag, got.tag):
|
127 |
+
return False
|
128 |
+
if not self.text_compare(want.text, got.text, True):
|
129 |
+
return False
|
130 |
+
if not self.text_compare(want.tail, got.tail, True):
|
131 |
+
return False
|
132 |
+
if 'any' not in want.attrib:
|
133 |
+
want_keys = sorted(want.attrib.keys())
|
134 |
+
got_keys = sorted(got.attrib.keys())
|
135 |
+
if want_keys != got_keys:
|
136 |
+
return False
|
137 |
+
for key in want_keys:
|
138 |
+
if not self.text_compare(want.attrib[key], got.attrib[key], False):
|
139 |
+
return False
|
140 |
+
if want.text != '...' or len(want):
|
141 |
+
want_children = list(want)
|
142 |
+
got_children = list(got)
|
143 |
+
while want_children or got_children:
|
144 |
+
if not want_children or not got_children:
|
145 |
+
return False
|
146 |
+
want_first = want_children.pop(0)
|
147 |
+
got_first = got_children.pop(0)
|
148 |
+
if not self.compare_docs(want_first, got_first):
|
149 |
+
return False
|
150 |
+
if not got_children and want_first.tail == '...':
|
151 |
+
break
|
152 |
+
return True
|
153 |
+
|
154 |
+
def text_compare(self, want, got, strip):
|
155 |
+
want = want or ''
|
156 |
+
got = got or ''
|
157 |
+
if strip:
|
158 |
+
want = norm_whitespace(want).strip()
|
159 |
+
got = norm_whitespace(got).strip()
|
160 |
+
want = '^%s$' % re.escape(want)
|
161 |
+
want = want.replace(r'\.\.\.', '.*')
|
162 |
+
if re.search(want, got):
|
163 |
+
return True
|
164 |
+
else:
|
165 |
+
return False
|
166 |
+
|
167 |
+
def tag_compare(self, want, got):
|
168 |
+
if want == 'any':
|
169 |
+
return True
|
170 |
+
if (not isinstance(want, (str, bytes))
|
171 |
+
or not isinstance(got, (str, bytes))):
|
172 |
+
return want == got
|
173 |
+
want = want or ''
|
174 |
+
got = got or ''
|
175 |
+
if want.startswith('{...}'):
|
176 |
+
# Ellipsis on the namespace
|
177 |
+
return want.split('}')[-1] == got.split('}')[-1]
|
178 |
+
else:
|
179 |
+
return want == got
|
180 |
+
|
181 |
+
def output_difference(self, example, got, optionflags):
|
182 |
+
want = example.want
|
183 |
+
parser = self.get_parser(want, got, optionflags)
|
184 |
+
errors = []
|
185 |
+
if parser is not None:
|
186 |
+
try:
|
187 |
+
want_doc = parser(want)
|
188 |
+
except etree.XMLSyntaxError:
|
189 |
+
e = sys.exc_info()[1]
|
190 |
+
errors.append('In example: %s' % e)
|
191 |
+
try:
|
192 |
+
got_doc = parser(got)
|
193 |
+
except etree.XMLSyntaxError:
|
194 |
+
e = sys.exc_info()[1]
|
195 |
+
errors.append('In actual output: %s' % e)
|
196 |
+
if parser is None or errors:
|
197 |
+
value = OutputChecker.output_difference(
|
198 |
+
self, example, got, optionflags)
|
199 |
+
if errors:
|
200 |
+
errors.append(value)
|
201 |
+
return '\n'.join(errors)
|
202 |
+
else:
|
203 |
+
return value
|
204 |
+
html = parser is html_fromstring
|
205 |
+
diff_parts = ['Expected:',
|
206 |
+
self.format_doc(want_doc, html, 2),
|
207 |
+
'Got:',
|
208 |
+
self.format_doc(got_doc, html, 2),
|
209 |
+
'Diff:',
|
210 |
+
self.collect_diff(want_doc, got_doc, html, 2)]
|
211 |
+
return '\n'.join(diff_parts)
|
212 |
+
|
213 |
+
def html_empty_tag(self, el, html=True):
|
214 |
+
if not html:
|
215 |
+
return False
|
216 |
+
if el.tag not in self.empty_tags:
|
217 |
+
return False
|
218 |
+
if el.text or len(el):
|
219 |
+
# This shouldn't happen (contents in an empty tag)
|
220 |
+
return False
|
221 |
+
return True
|
222 |
+
|
223 |
+
def format_doc(self, doc, html, indent, prefix=''):
|
224 |
+
parts = []
|
225 |
+
if not len(doc):
|
226 |
+
# No children...
|
227 |
+
parts.append(' '*indent)
|
228 |
+
parts.append(prefix)
|
229 |
+
parts.append(self.format_tag(doc))
|
230 |
+
if not self.html_empty_tag(doc, html):
|
231 |
+
if strip(doc.text):
|
232 |
+
parts.append(self.format_text(doc.text))
|
233 |
+
parts.append(self.format_end_tag(doc))
|
234 |
+
if strip(doc.tail):
|
235 |
+
parts.append(self.format_text(doc.tail))
|
236 |
+
parts.append('\n')
|
237 |
+
return ''.join(parts)
|
238 |
+
parts.append(' '*indent)
|
239 |
+
parts.append(prefix)
|
240 |
+
parts.append(self.format_tag(doc))
|
241 |
+
if not self.html_empty_tag(doc, html):
|
242 |
+
parts.append('\n')
|
243 |
+
if strip(doc.text):
|
244 |
+
parts.append(' '*indent)
|
245 |
+
parts.append(self.format_text(doc.text))
|
246 |
+
parts.append('\n')
|
247 |
+
for el in doc:
|
248 |
+
parts.append(self.format_doc(el, html, indent+2))
|
249 |
+
parts.append(' '*indent)
|
250 |
+
parts.append(self.format_end_tag(doc))
|
251 |
+
parts.append('\n')
|
252 |
+
if strip(doc.tail):
|
253 |
+
parts.append(' '*indent)
|
254 |
+
parts.append(self.format_text(doc.tail))
|
255 |
+
parts.append('\n')
|
256 |
+
return ''.join(parts)
|
257 |
+
|
258 |
+
def format_text(self, text, strip=True):
|
259 |
+
if text is None:
|
260 |
+
return ''
|
261 |
+
if strip:
|
262 |
+
text = text.strip()
|
263 |
+
return html_escape(text, 1)
|
264 |
+
|
265 |
+
def format_tag(self, el):
|
266 |
+
attrs = []
|
267 |
+
if isinstance(el, etree.CommentBase):
|
268 |
+
# FIXME: probably PIs should be handled specially too?
|
269 |
+
return '<!--'
|
270 |
+
for name, value in sorted(el.attrib.items()):
|
271 |
+
attrs.append('%s="%s"' % (name, self.format_text(value, False)))
|
272 |
+
if not attrs:
|
273 |
+
return '<%s>' % el.tag
|
274 |
+
return '<%s %s>' % (el.tag, ' '.join(attrs))
|
275 |
+
|
276 |
+
def format_end_tag(self, el):
|
277 |
+
if isinstance(el, etree.CommentBase):
|
278 |
+
# FIXME: probably PIs should be handled specially too?
|
279 |
+
return '-->'
|
280 |
+
return '</%s>' % el.tag
|
281 |
+
|
282 |
+
def collect_diff(self, want, got, html, indent):
|
283 |
+
parts = []
|
284 |
+
if not len(want) and not len(got):
|
285 |
+
parts.append(' '*indent)
|
286 |
+
parts.append(self.collect_diff_tag(want, got))
|
287 |
+
if not self.html_empty_tag(got, html):
|
288 |
+
parts.append(self.collect_diff_text(want.text, got.text))
|
289 |
+
parts.append(self.collect_diff_end_tag(want, got))
|
290 |
+
parts.append(self.collect_diff_text(want.tail, got.tail))
|
291 |
+
parts.append('\n')
|
292 |
+
return ''.join(parts)
|
293 |
+
parts.append(' '*indent)
|
294 |
+
parts.append(self.collect_diff_tag(want, got))
|
295 |
+
parts.append('\n')
|
296 |
+
if strip(want.text) or strip(got.text):
|
297 |
+
parts.append(' '*indent)
|
298 |
+
parts.append(self.collect_diff_text(want.text, got.text))
|
299 |
+
parts.append('\n')
|
300 |
+
want_children = list(want)
|
301 |
+
got_children = list(got)
|
302 |
+
while want_children or got_children:
|
303 |
+
if not want_children:
|
304 |
+
parts.append(self.format_doc(got_children.pop(0), html, indent+2, '+'))
|
305 |
+
continue
|
306 |
+
if not got_children:
|
307 |
+
parts.append(self.format_doc(want_children.pop(0), html, indent+2, '-'))
|
308 |
+
continue
|
309 |
+
parts.append(self.collect_diff(
|
310 |
+
want_children.pop(0), got_children.pop(0), html, indent+2))
|
311 |
+
parts.append(' '*indent)
|
312 |
+
parts.append(self.collect_diff_end_tag(want, got))
|
313 |
+
parts.append('\n')
|
314 |
+
if strip(want.tail) or strip(got.tail):
|
315 |
+
parts.append(' '*indent)
|
316 |
+
parts.append(self.collect_diff_text(want.tail, got.tail))
|
317 |
+
parts.append('\n')
|
318 |
+
return ''.join(parts)
|
319 |
+
|
320 |
+
def collect_diff_tag(self, want, got):
|
321 |
+
if not self.tag_compare(want.tag, got.tag):
|
322 |
+
tag = '%s (got: %s)' % (want.tag, got.tag)
|
323 |
+
else:
|
324 |
+
tag = got.tag
|
325 |
+
attrs = []
|
326 |
+
any = want.tag == 'any' or 'any' in want.attrib
|
327 |
+
for name, value in sorted(got.attrib.items()):
|
328 |
+
if name not in want.attrib and not any:
|
329 |
+
attrs.append('+%s="%s"' % (name, self.format_text(value, False)))
|
330 |
+
else:
|
331 |
+
if name in want.attrib:
|
332 |
+
text = self.collect_diff_text(want.attrib[name], value, False)
|
333 |
+
else:
|
334 |
+
text = self.format_text(value, False)
|
335 |
+
attrs.append('%s="%s"' % (name, text))
|
336 |
+
if not any:
|
337 |
+
for name, value in sorted(want.attrib.items()):
|
338 |
+
if name in got.attrib:
|
339 |
+
continue
|
340 |
+
attrs.append('-%s="%s"' % (name, self.format_text(value, False)))
|
341 |
+
if attrs:
|
342 |
+
tag = '<%s %s>' % (tag, ' '.join(attrs))
|
343 |
+
else:
|
344 |
+
tag = '<%s>' % tag
|
345 |
+
return tag
|
346 |
+
|
347 |
+
def collect_diff_end_tag(self, want, got):
|
348 |
+
if want.tag != got.tag:
|
349 |
+
tag = '%s (got: %s)' % (want.tag, got.tag)
|
350 |
+
else:
|
351 |
+
tag = got.tag
|
352 |
+
return '</%s>' % tag
|
353 |
+
|
354 |
+
def collect_diff_text(self, want, got, strip=True):
|
355 |
+
if self.text_compare(want, got, strip):
|
356 |
+
if not got:
|
357 |
+
return ''
|
358 |
+
return self.format_text(got, strip)
|
359 |
+
text = '%s (got: %s)' % (want, got)
|
360 |
+
return self.format_text(text, strip)
|
361 |
+
|
362 |
+
class LHTMLOutputChecker(LXMLOutputChecker):
|
363 |
+
def get_default_parser(self):
|
364 |
+
return html_fromstring
|
365 |
+
|
366 |
+
def install(html=False):
|
367 |
+
"""
|
368 |
+
Install doctestcompare for all future doctests.
|
369 |
+
|
370 |
+
If html is true, then by default the HTML parser will be used;
|
371 |
+
otherwise the XML parser is used.
|
372 |
+
"""
|
373 |
+
if html:
|
374 |
+
doctest.OutputChecker = LHTMLOutputChecker
|
375 |
+
else:
|
376 |
+
doctest.OutputChecker = LXMLOutputChecker
|
377 |
+
|
378 |
+
def temp_install(html=False, del_module=None):
|
379 |
+
"""
|
380 |
+
Use this *inside* a doctest to enable this checker for this
|
381 |
+
doctest only.
|
382 |
+
|
383 |
+
If html is true, then by default the HTML parser will be used;
|
384 |
+
otherwise the XML parser is used.
|
385 |
+
"""
|
386 |
+
if html:
|
387 |
+
Checker = LHTMLOutputChecker
|
388 |
+
else:
|
389 |
+
Checker = LXMLOutputChecker
|
390 |
+
frame = _find_doctest_frame()
|
391 |
+
dt_self = frame.f_locals['self']
|
392 |
+
checker = Checker()
|
393 |
+
old_checker = dt_self._checker
|
394 |
+
dt_self._checker = checker
|
395 |
+
# The unfortunate thing is that there is a local variable 'check'
|
396 |
+
# in the function that runs the doctests, that is a bound method
|
397 |
+
# into the output checker. We have to update that. We can't
|
398 |
+
# modify the frame, so we have to modify the object in place. The
|
399 |
+
# only way to do this is to actually change the func_code
|
400 |
+
# attribute of the method. We change it, and then wait for
|
401 |
+
# __record_outcome to be run, which signals the end of the __run
|
402 |
+
# method, at which point we restore the previous check_output
|
403 |
+
# implementation.
|
404 |
+
check_func = frame.f_locals['check'].__func__
|
405 |
+
checker_check_func = checker.check_output.__func__
|
406 |
+
# Because we can't patch up func_globals, this is the only global
|
407 |
+
# in check_output that we care about:
|
408 |
+
doctest.etree = etree
|
409 |
+
_RestoreChecker(dt_self, old_checker, checker,
|
410 |
+
check_func, checker_check_func,
|
411 |
+
del_module)
|
412 |
+
|
413 |
+
class _RestoreChecker:
|
414 |
+
def __init__(self, dt_self, old_checker, new_checker, check_func, clone_func,
|
415 |
+
del_module):
|
416 |
+
self.dt_self = dt_self
|
417 |
+
self.checker = old_checker
|
418 |
+
self.checker._temp_call_super_check_output = self.call_super
|
419 |
+
self.checker._temp_override_self = new_checker
|
420 |
+
self.check_func = check_func
|
421 |
+
self.clone_func = clone_func
|
422 |
+
self.del_module = del_module
|
423 |
+
self.install_clone()
|
424 |
+
self.install_dt_self()
|
425 |
+
def install_clone(self):
|
426 |
+
self.func_code = self.check_func.__code__
|
427 |
+
self.func_globals = self.check_func.__globals__
|
428 |
+
self.check_func.__code__ = self.clone_func.__code__
|
429 |
+
def uninstall_clone(self):
|
430 |
+
self.check_func.__code__ = self.func_code
|
431 |
+
def install_dt_self(self):
|
432 |
+
self.prev_func = self.dt_self._DocTestRunner__record_outcome
|
433 |
+
self.dt_self._DocTestRunner__record_outcome = self
|
434 |
+
def uninstall_dt_self(self):
|
435 |
+
self.dt_self._DocTestRunner__record_outcome = self.prev_func
|
436 |
+
def uninstall_module(self):
|
437 |
+
if self.del_module:
|
438 |
+
import sys
|
439 |
+
del sys.modules[self.del_module]
|
440 |
+
if '.' in self.del_module:
|
441 |
+
package, module = self.del_module.rsplit('.', 1)
|
442 |
+
package_mod = sys.modules[package]
|
443 |
+
delattr(package_mod, module)
|
444 |
+
def __call__(self, *args, **kw):
|
445 |
+
self.uninstall_clone()
|
446 |
+
self.uninstall_dt_self()
|
447 |
+
del self.checker._temp_override_self
|
448 |
+
del self.checker._temp_call_super_check_output
|
449 |
+
result = self.prev_func(*args, **kw)
|
450 |
+
self.uninstall_module()
|
451 |
+
return result
|
452 |
+
def call_super(self, *args, **kw):
|
453 |
+
self.uninstall_clone()
|
454 |
+
try:
|
455 |
+
return self.check_func(*args, **kw)
|
456 |
+
finally:
|
457 |
+
self.install_clone()
|
458 |
+
|
459 |
+
def _find_doctest_frame():
|
460 |
+
import sys
|
461 |
+
frame = sys._getframe(1)
|
462 |
+
while frame:
|
463 |
+
l = frame.f_locals
|
464 |
+
if 'BOOM' in l:
|
465 |
+
# Sign of doctest
|
466 |
+
return frame
|
467 |
+
frame = frame.f_back
|
468 |
+
raise LookupError(
|
469 |
+
"Could not find doctest (only use this function *inside* a doctest)")
|
470 |
+
|
471 |
+
__test__ = {
|
472 |
+
'basic': '''
|
473 |
+
>>> temp_install()
|
474 |
+
>>> print """<xml a="1" b="2">stuff</xml>"""
|
475 |
+
<xml b="2" a="1">...</xml>
|
476 |
+
>>> print """<xml xmlns="http://example.com"><tag attr="bar" /></xml>"""
|
477 |
+
<xml xmlns="...">
|
478 |
+
<tag attr="..." />
|
479 |
+
</xml>
|
480 |
+
>>> print """<xml>blahblahblah<foo /></xml>""" # doctest: +NOPARSE_MARKUP, +ELLIPSIS
|
481 |
+
<xml>...foo /></xml>
|
482 |
+
'''}
|
483 |
+
|
484 |
+
if __name__ == '__main__':
|
485 |
+
import doctest
|
486 |
+
doctest.testmod()
|
487 |
+
|
488 |
+
|
llmeval-env/lib/python3.10/site-packages/lxml/dtd.pxi
ADDED
@@ -0,0 +1,478 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# support for DTD validation
|
2 |
+
from lxml.includes cimport dtdvalid
|
3 |
+
|
4 |
+
cdef class DTDError(LxmlError):
|
5 |
+
"""Base class for DTD errors.
|
6 |
+
"""
|
7 |
+
|
8 |
+
cdef class DTDParseError(DTDError):
|
9 |
+
"""Error while parsing a DTD.
|
10 |
+
"""
|
11 |
+
|
12 |
+
cdef class DTDValidateError(DTDError):
|
13 |
+
"""Error while validating an XML document with a DTD.
|
14 |
+
"""
|
15 |
+
|
16 |
+
|
17 |
+
cdef inline int _assertValidDTDNode(node, void *c_node) except -1:
|
18 |
+
assert c_node is not NULL, "invalid DTD proxy at %s" % id(node)
|
19 |
+
|
20 |
+
|
21 |
+
@cython.final
|
22 |
+
@cython.internal
|
23 |
+
@cython.freelist(8)
|
24 |
+
cdef class _DTDElementContentDecl:
|
25 |
+
cdef DTD _dtd
|
26 |
+
cdef tree.xmlElementContent* _c_node
|
27 |
+
|
28 |
+
def __repr__(self):
|
29 |
+
return "<%s.%s object name=%r type=%r occur=%r at 0x%x>" % (self.__class__.__module__, self.__class__.__name__, self.name, self.type, self.occur, id(self))
|
30 |
+
|
31 |
+
@property
|
32 |
+
def name(self):
|
33 |
+
_assertValidDTDNode(self, self._c_node)
|
34 |
+
return funicodeOrNone(self._c_node.name)
|
35 |
+
|
36 |
+
@property
|
37 |
+
def type(self):
|
38 |
+
_assertValidDTDNode(self, self._c_node)
|
39 |
+
cdef int type = self._c_node.type
|
40 |
+
if type == tree.XML_ELEMENT_CONTENT_PCDATA:
|
41 |
+
return "pcdata"
|
42 |
+
elif type == tree.XML_ELEMENT_CONTENT_ELEMENT:
|
43 |
+
return "element"
|
44 |
+
elif type == tree.XML_ELEMENT_CONTENT_SEQ:
|
45 |
+
return "seq"
|
46 |
+
elif type == tree.XML_ELEMENT_CONTENT_OR:
|
47 |
+
return "or"
|
48 |
+
else:
|
49 |
+
return None
|
50 |
+
|
51 |
+
@property
|
52 |
+
def occur(self):
|
53 |
+
_assertValidDTDNode(self, self._c_node)
|
54 |
+
cdef int occur = self._c_node.ocur
|
55 |
+
if occur == tree.XML_ELEMENT_CONTENT_ONCE:
|
56 |
+
return "once"
|
57 |
+
elif occur == tree.XML_ELEMENT_CONTENT_OPT:
|
58 |
+
return "opt"
|
59 |
+
elif occur == tree.XML_ELEMENT_CONTENT_MULT:
|
60 |
+
return "mult"
|
61 |
+
elif occur == tree.XML_ELEMENT_CONTENT_PLUS:
|
62 |
+
return "plus"
|
63 |
+
else:
|
64 |
+
return None
|
65 |
+
|
66 |
+
@property
|
67 |
+
def left(self):
|
68 |
+
_assertValidDTDNode(self, self._c_node)
|
69 |
+
c1 = self._c_node.c1
|
70 |
+
if c1:
|
71 |
+
node = <_DTDElementContentDecl>_DTDElementContentDecl.__new__(_DTDElementContentDecl)
|
72 |
+
node._dtd = self._dtd
|
73 |
+
node._c_node = <tree.xmlElementContent*>c1
|
74 |
+
return node
|
75 |
+
else:
|
76 |
+
return None
|
77 |
+
|
78 |
+
@property
|
79 |
+
def right(self):
|
80 |
+
_assertValidDTDNode(self, self._c_node)
|
81 |
+
c2 = self._c_node.c2
|
82 |
+
if c2:
|
83 |
+
node = <_DTDElementContentDecl>_DTDElementContentDecl.__new__(_DTDElementContentDecl)
|
84 |
+
node._dtd = self._dtd
|
85 |
+
node._c_node = <tree.xmlElementContent*>c2
|
86 |
+
return node
|
87 |
+
else:
|
88 |
+
return None
|
89 |
+
|
90 |
+
|
91 |
+
@cython.final
|
92 |
+
@cython.internal
|
93 |
+
@cython.freelist(8)
|
94 |
+
cdef class _DTDAttributeDecl:
|
95 |
+
cdef DTD _dtd
|
96 |
+
cdef tree.xmlAttribute* _c_node
|
97 |
+
|
98 |
+
def __repr__(self):
|
99 |
+
return "<%s.%s object name=%r elemname=%r prefix=%r type=%r default=%r default_value=%r at 0x%x>" % (self.__class__.__module__, self.__class__.__name__, self.name, self.elemname, self.prefix, self.type, self.default, self.default_value, id(self))
|
100 |
+
|
101 |
+
@property
|
102 |
+
def name(self):
|
103 |
+
_assertValidDTDNode(self, self._c_node)
|
104 |
+
return funicodeOrNone(self._c_node.name)
|
105 |
+
|
106 |
+
@property
|
107 |
+
def elemname(self):
|
108 |
+
_assertValidDTDNode(self, self._c_node)
|
109 |
+
return funicodeOrNone(self._c_node.elem)
|
110 |
+
|
111 |
+
@property
|
112 |
+
def prefix(self):
|
113 |
+
_assertValidDTDNode(self, self._c_node)
|
114 |
+
return funicodeOrNone(self._c_node.prefix)
|
115 |
+
|
116 |
+
@property
|
117 |
+
def type(self):
|
118 |
+
_assertValidDTDNode(self, self._c_node)
|
119 |
+
cdef int type = self._c_node.atype
|
120 |
+
if type == tree.XML_ATTRIBUTE_CDATA:
|
121 |
+
return "cdata"
|
122 |
+
elif type == tree.XML_ATTRIBUTE_ID:
|
123 |
+
return "id"
|
124 |
+
elif type == tree.XML_ATTRIBUTE_IDREF:
|
125 |
+
return "idref"
|
126 |
+
elif type == tree.XML_ATTRIBUTE_IDREFS:
|
127 |
+
return "idrefs"
|
128 |
+
elif type == tree.XML_ATTRIBUTE_ENTITY:
|
129 |
+
return "entity"
|
130 |
+
elif type == tree.XML_ATTRIBUTE_ENTITIES:
|
131 |
+
return "entities"
|
132 |
+
elif type == tree.XML_ATTRIBUTE_NMTOKEN:
|
133 |
+
return "nmtoken"
|
134 |
+
elif type == tree.XML_ATTRIBUTE_NMTOKENS:
|
135 |
+
return "nmtokens"
|
136 |
+
elif type == tree.XML_ATTRIBUTE_ENUMERATION:
|
137 |
+
return "enumeration"
|
138 |
+
elif type == tree.XML_ATTRIBUTE_NOTATION:
|
139 |
+
return "notation"
|
140 |
+
else:
|
141 |
+
return None
|
142 |
+
|
143 |
+
@property
|
144 |
+
def default(self):
|
145 |
+
_assertValidDTDNode(self, self._c_node)
|
146 |
+
cdef int default = self._c_node.def_
|
147 |
+
if default == tree.XML_ATTRIBUTE_NONE:
|
148 |
+
return "none"
|
149 |
+
elif default == tree.XML_ATTRIBUTE_REQUIRED:
|
150 |
+
return "required"
|
151 |
+
elif default == tree.XML_ATTRIBUTE_IMPLIED:
|
152 |
+
return "implied"
|
153 |
+
elif default == tree.XML_ATTRIBUTE_FIXED:
|
154 |
+
return "fixed"
|
155 |
+
else:
|
156 |
+
return None
|
157 |
+
|
158 |
+
@property
|
159 |
+
def default_value(self):
|
160 |
+
_assertValidDTDNode(self, self._c_node)
|
161 |
+
return funicodeOrNone(self._c_node.defaultValue)
|
162 |
+
|
163 |
+
def itervalues(self):
|
164 |
+
_assertValidDTDNode(self, self._c_node)
|
165 |
+
cdef tree.xmlEnumeration *c_node = self._c_node.tree
|
166 |
+
while c_node is not NULL:
|
167 |
+
yield funicode(c_node.name)
|
168 |
+
c_node = c_node.next
|
169 |
+
|
170 |
+
def values(self):
|
171 |
+
return list(self.itervalues())
|
172 |
+
|
173 |
+
|
174 |
+
@cython.final
|
175 |
+
@cython.internal
|
176 |
+
@cython.freelist(8)
|
177 |
+
cdef class _DTDElementDecl:
|
178 |
+
cdef DTD _dtd
|
179 |
+
cdef tree.xmlElement* _c_node
|
180 |
+
|
181 |
+
def __repr__(self):
|
182 |
+
return "<%s.%s object name=%r prefix=%r type=%r at 0x%x>" % (self.__class__.__module__, self.__class__.__name__, self.name, self.prefix, self.type, id(self))
|
183 |
+
|
184 |
+
@property
|
185 |
+
def name(self):
|
186 |
+
_assertValidDTDNode(self, self._c_node)
|
187 |
+
return funicodeOrNone(self._c_node.name)
|
188 |
+
|
189 |
+
@property
|
190 |
+
def prefix(self):
|
191 |
+
_assertValidDTDNode(self, self._c_node)
|
192 |
+
return funicodeOrNone(self._c_node.prefix)
|
193 |
+
|
194 |
+
@property
|
195 |
+
def type(self):
|
196 |
+
_assertValidDTDNode(self, self._c_node)
|
197 |
+
cdef int type = self._c_node.etype
|
198 |
+
if type == tree.XML_ELEMENT_TYPE_UNDEFINED:
|
199 |
+
return "undefined"
|
200 |
+
elif type == tree.XML_ELEMENT_TYPE_EMPTY:
|
201 |
+
return "empty"
|
202 |
+
elif type == tree.XML_ELEMENT_TYPE_ANY:
|
203 |
+
return "any"
|
204 |
+
elif type == tree.XML_ELEMENT_TYPE_MIXED:
|
205 |
+
return "mixed"
|
206 |
+
elif type == tree.XML_ELEMENT_TYPE_ELEMENT:
|
207 |
+
return "element"
|
208 |
+
else:
|
209 |
+
return None
|
210 |
+
|
211 |
+
@property
|
212 |
+
def content(self):
|
213 |
+
_assertValidDTDNode(self, self._c_node)
|
214 |
+
cdef tree.xmlElementContent *content = self._c_node.content
|
215 |
+
if content:
|
216 |
+
node = <_DTDElementContentDecl>_DTDElementContentDecl.__new__(_DTDElementContentDecl)
|
217 |
+
node._dtd = self._dtd
|
218 |
+
node._c_node = content
|
219 |
+
return node
|
220 |
+
else:
|
221 |
+
return None
|
222 |
+
|
223 |
+
def iterattributes(self):
|
224 |
+
_assertValidDTDNode(self, self._c_node)
|
225 |
+
cdef tree.xmlAttribute *c_node = self._c_node.attributes
|
226 |
+
while c_node:
|
227 |
+
node = <_DTDAttributeDecl>_DTDAttributeDecl.__new__(_DTDAttributeDecl)
|
228 |
+
node._dtd = self._dtd
|
229 |
+
node._c_node = c_node
|
230 |
+
yield node
|
231 |
+
c_node = c_node.nexth
|
232 |
+
|
233 |
+
def attributes(self):
|
234 |
+
return list(self.iterattributes())
|
235 |
+
|
236 |
+
|
237 |
+
@cython.final
|
238 |
+
@cython.internal
|
239 |
+
@cython.freelist(8)
|
240 |
+
cdef class _DTDEntityDecl:
|
241 |
+
cdef DTD _dtd
|
242 |
+
cdef tree.xmlEntity* _c_node
|
243 |
+
def __repr__(self):
|
244 |
+
return "<%s.%s object name=%r at 0x%x>" % (self.__class__.__module__, self.__class__.__name__, self.name, id(self))
|
245 |
+
|
246 |
+
@property
|
247 |
+
def name(self):
|
248 |
+
_assertValidDTDNode(self, self._c_node)
|
249 |
+
return funicodeOrNone(self._c_node.name)
|
250 |
+
|
251 |
+
@property
|
252 |
+
def orig(self):
|
253 |
+
_assertValidDTDNode(self, self._c_node)
|
254 |
+
return funicodeOrNone(self._c_node.orig)
|
255 |
+
|
256 |
+
@property
|
257 |
+
def content(self):
|
258 |
+
_assertValidDTDNode(self, self._c_node)
|
259 |
+
return funicodeOrNone(self._c_node.content)
|
260 |
+
|
261 |
+
@property
|
262 |
+
def system_url(self):
|
263 |
+
_assertValidDTDNode(self, self._c_node)
|
264 |
+
return funicodeOrNone(self._c_node.SystemID)
|
265 |
+
|
266 |
+
|
267 |
+
################################################################################
|
268 |
+
# DTD
|
269 |
+
|
270 |
+
cdef class DTD(_Validator):
|
271 |
+
"""DTD(self, file=None, external_id=None)
|
272 |
+
A DTD validator.
|
273 |
+
|
274 |
+
Can load from filesystem directly given a filename or file-like object.
|
275 |
+
Alternatively, pass the keyword parameter ``external_id`` to load from a
|
276 |
+
catalog.
|
277 |
+
"""
|
278 |
+
cdef tree.xmlDtd* _c_dtd
|
279 |
+
def __init__(self, file=None, *, external_id=None):
|
280 |
+
_Validator.__init__(self)
|
281 |
+
if file is not None:
|
282 |
+
file = _getFSPathOrObject(file)
|
283 |
+
if _isString(file):
|
284 |
+
file = _encodeFilename(file)
|
285 |
+
with self._error_log:
|
286 |
+
orig_loader = _register_document_loader()
|
287 |
+
self._c_dtd = xmlparser.xmlParseDTD(NULL, _xcstr(file))
|
288 |
+
_reset_document_loader(orig_loader)
|
289 |
+
elif hasattr(file, 'read'):
|
290 |
+
orig_loader = _register_document_loader()
|
291 |
+
self._c_dtd = _parseDtdFromFilelike(file)
|
292 |
+
_reset_document_loader(orig_loader)
|
293 |
+
else:
|
294 |
+
raise DTDParseError, "file must be a filename, file-like or path-like object"
|
295 |
+
elif external_id is not None:
|
296 |
+
with self._error_log:
|
297 |
+
orig_loader = _register_document_loader()
|
298 |
+
self._c_dtd = xmlparser.xmlParseDTD(<const_xmlChar*>external_id, NULL)
|
299 |
+
_reset_document_loader(orig_loader)
|
300 |
+
else:
|
301 |
+
raise DTDParseError, "either filename or external ID required"
|
302 |
+
|
303 |
+
if self._c_dtd is NULL:
|
304 |
+
raise DTDParseError(
|
305 |
+
self._error_log._buildExceptionMessage("error parsing DTD"),
|
306 |
+
self._error_log)
|
307 |
+
|
308 |
+
@property
|
309 |
+
def name(self):
|
310 |
+
if self._c_dtd is NULL:
|
311 |
+
return None
|
312 |
+
return funicodeOrNone(self._c_dtd.name)
|
313 |
+
|
314 |
+
@property
|
315 |
+
def external_id(self):
|
316 |
+
if self._c_dtd is NULL:
|
317 |
+
return None
|
318 |
+
return funicodeOrNone(self._c_dtd.ExternalID)
|
319 |
+
|
320 |
+
@property
|
321 |
+
def system_url(self):
|
322 |
+
if self._c_dtd is NULL:
|
323 |
+
return None
|
324 |
+
return funicodeOrNone(self._c_dtd.SystemID)
|
325 |
+
|
326 |
+
def iterelements(self):
|
327 |
+
cdef tree.xmlNode *c_node = self._c_dtd.children if self._c_dtd is not NULL else NULL
|
328 |
+
while c_node is not NULL:
|
329 |
+
if c_node.type == tree.XML_ELEMENT_DECL:
|
330 |
+
node = _DTDElementDecl()
|
331 |
+
node._dtd = self
|
332 |
+
node._c_node = <tree.xmlElement*>c_node
|
333 |
+
yield node
|
334 |
+
c_node = c_node.next
|
335 |
+
|
336 |
+
def elements(self):
|
337 |
+
return list(self.iterelements())
|
338 |
+
|
339 |
+
def iterentities(self):
|
340 |
+
cdef tree.xmlNode *c_node = self._c_dtd.children if self._c_dtd is not NULL else NULL
|
341 |
+
while c_node is not NULL:
|
342 |
+
if c_node.type == tree.XML_ENTITY_DECL:
|
343 |
+
node = _DTDEntityDecl()
|
344 |
+
node._dtd = self
|
345 |
+
node._c_node = <tree.xmlEntity*>c_node
|
346 |
+
yield node
|
347 |
+
c_node = c_node.next
|
348 |
+
|
349 |
+
def entities(self):
|
350 |
+
return list(self.iterentities())
|
351 |
+
|
352 |
+
def __dealloc__(self):
|
353 |
+
tree.xmlFreeDtd(self._c_dtd)
|
354 |
+
|
355 |
+
def __call__(self, etree):
|
356 |
+
"""__call__(self, etree)
|
357 |
+
|
358 |
+
Validate doc using the DTD.
|
359 |
+
|
360 |
+
Returns true if the document is valid, false if not.
|
361 |
+
"""
|
362 |
+
cdef _Document doc
|
363 |
+
cdef _Element root_node
|
364 |
+
cdef xmlDoc* c_doc
|
365 |
+
cdef dtdvalid.xmlValidCtxt* valid_ctxt
|
366 |
+
cdef int ret = -1
|
367 |
+
|
368 |
+
assert self._c_dtd is not NULL, "DTD not initialised"
|
369 |
+
doc = _documentOrRaise(etree)
|
370 |
+
root_node = _rootNodeOrRaise(etree)
|
371 |
+
|
372 |
+
valid_ctxt = dtdvalid.xmlNewValidCtxt()
|
373 |
+
if valid_ctxt is NULL:
|
374 |
+
raise DTDError("Failed to create validation context")
|
375 |
+
|
376 |
+
# work around error reporting bug in libxml2 <= 2.9.1 (and later?)
|
377 |
+
# https://bugzilla.gnome.org/show_bug.cgi?id=724903
|
378 |
+
valid_ctxt.error = <dtdvalid.xmlValidityErrorFunc>_nullGenericErrorFunc
|
379 |
+
valid_ctxt.userData = NULL
|
380 |
+
|
381 |
+
try:
|
382 |
+
with self._error_log:
|
383 |
+
c_doc = _fakeRootDoc(doc._c_doc, root_node._c_node)
|
384 |
+
ret = dtdvalid.xmlValidateDtd(valid_ctxt, c_doc, self._c_dtd)
|
385 |
+
_destroyFakeDoc(doc._c_doc, c_doc)
|
386 |
+
finally:
|
387 |
+
dtdvalid.xmlFreeValidCtxt(valid_ctxt)
|
388 |
+
|
389 |
+
if ret == -1:
|
390 |
+
raise DTDValidateError("Internal error in DTD validation",
|
391 |
+
self._error_log)
|
392 |
+
return ret == 1
|
393 |
+
|
394 |
+
|
395 |
+
cdef tree.xmlDtd* _parseDtdFromFilelike(file) except NULL:
|
396 |
+
cdef _ExceptionContext exc_context
|
397 |
+
cdef _FileReaderContext dtd_parser
|
398 |
+
cdef _ErrorLog error_log
|
399 |
+
cdef tree.xmlDtd* c_dtd = NULL
|
400 |
+
exc_context = _ExceptionContext()
|
401 |
+
dtd_parser = _FileReaderContext(file, exc_context, None)
|
402 |
+
error_log = _ErrorLog()
|
403 |
+
|
404 |
+
with error_log:
|
405 |
+
c_dtd = dtd_parser._readDtd()
|
406 |
+
|
407 |
+
exc_context._raise_if_stored()
|
408 |
+
if c_dtd is NULL:
|
409 |
+
raise DTDParseError("error parsing DTD", error_log)
|
410 |
+
return c_dtd
|
411 |
+
|
412 |
+
cdef DTD _dtdFactory(tree.xmlDtd* c_dtd):
|
413 |
+
# do not run through DTD.__init__()!
|
414 |
+
cdef DTD dtd
|
415 |
+
if c_dtd is NULL:
|
416 |
+
return None
|
417 |
+
dtd = DTD.__new__(DTD)
|
418 |
+
dtd._c_dtd = _copyDtd(c_dtd)
|
419 |
+
_Validator.__init__(dtd)
|
420 |
+
return dtd
|
421 |
+
|
422 |
+
|
423 |
+
cdef tree.xmlDtd* _copyDtd(tree.xmlDtd* c_orig_dtd) except NULL:
|
424 |
+
"""
|
425 |
+
Copy a DTD. libxml2 (currently) fails to set up the element->attributes
|
426 |
+
links when copying DTDs, so we have to rebuild them here.
|
427 |
+
"""
|
428 |
+
c_dtd = tree.xmlCopyDtd(c_orig_dtd)
|
429 |
+
if not c_dtd:
|
430 |
+
raise MemoryError
|
431 |
+
cdef tree.xmlNode* c_node = c_dtd.children
|
432 |
+
while c_node:
|
433 |
+
if c_node.type == tree.XML_ATTRIBUTE_DECL:
|
434 |
+
_linkDtdAttribute(c_dtd, <tree.xmlAttribute*>c_node)
|
435 |
+
c_node = c_node.next
|
436 |
+
return c_dtd
|
437 |
+
|
438 |
+
|
439 |
+
cdef void _linkDtdAttribute(tree.xmlDtd* c_dtd, tree.xmlAttribute* c_attr) noexcept:
|
440 |
+
"""
|
441 |
+
Create the link to the DTD attribute declaration from the corresponding
|
442 |
+
element declaration.
|
443 |
+
"""
|
444 |
+
c_elem = dtdvalid.xmlGetDtdElementDesc(c_dtd, c_attr.elem)
|
445 |
+
if not c_elem:
|
446 |
+
# no such element? something is wrong with the DTD ...
|
447 |
+
return
|
448 |
+
c_pos = c_elem.attributes
|
449 |
+
if not c_pos:
|
450 |
+
c_elem.attributes = c_attr
|
451 |
+
c_attr.nexth = NULL
|
452 |
+
return
|
453 |
+
# libxml2 keeps namespace declarations first, and we need to make
|
454 |
+
# sure we don't re-insert attributes that are already there
|
455 |
+
if _isDtdNsDecl(c_attr):
|
456 |
+
if not _isDtdNsDecl(c_pos):
|
457 |
+
c_elem.attributes = c_attr
|
458 |
+
c_attr.nexth = c_pos
|
459 |
+
return
|
460 |
+
while c_pos != c_attr and c_pos.nexth and _isDtdNsDecl(c_pos.nexth):
|
461 |
+
c_pos = c_pos.nexth
|
462 |
+
else:
|
463 |
+
# append at end
|
464 |
+
while c_pos != c_attr and c_pos.nexth:
|
465 |
+
c_pos = c_pos.nexth
|
466 |
+
if c_pos == c_attr:
|
467 |
+
return
|
468 |
+
c_attr.nexth = c_pos.nexth
|
469 |
+
c_pos.nexth = c_attr
|
470 |
+
|
471 |
+
|
472 |
+
cdef bint _isDtdNsDecl(tree.xmlAttribute* c_attr) noexcept:
|
473 |
+
if cstring_h.strcmp(<const_char*>c_attr.name, "xmlns") == 0:
|
474 |
+
return True
|
475 |
+
if (c_attr.prefix is not NULL and
|
476 |
+
cstring_h.strcmp(<const_char*>c_attr.prefix, "xmlns") == 0):
|
477 |
+
return True
|
478 |
+
return False
|
llmeval-env/lib/python3.10/site-packages/lxml/etree_api.h
ADDED
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/* Generated by Cython 3.0.10 */
|
2 |
+
|
3 |
+
#ifndef __PYX_HAVE_API__lxml__etree
|
4 |
+
#define __PYX_HAVE_API__lxml__etree
|
5 |
+
#ifdef __MINGW64__
|
6 |
+
#define MS_WIN64
|
7 |
+
#endif
|
8 |
+
#include "Python.h"
|
9 |
+
#include "etree.h"
|
10 |
+
|
11 |
+
static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_deepcopyNodeToDocument)(struct LxmlDocument *, xmlNode *) = 0;
|
12 |
+
#define deepcopyNodeToDocument __pyx_api_f_4lxml_5etree_deepcopyNodeToDocument
|
13 |
+
static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_elementTreeFactory)(struct LxmlElement *) = 0;
|
14 |
+
#define elementTreeFactory __pyx_api_f_4lxml_5etree_elementTreeFactory
|
15 |
+
static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_newElementTree)(struct LxmlElement *, PyObject *) = 0;
|
16 |
+
#define newElementTree __pyx_api_f_4lxml_5etree_newElementTree
|
17 |
+
static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_adoptExternalDocument)(xmlDoc *, PyObject *, int) = 0;
|
18 |
+
#define adoptExternalDocument __pyx_api_f_4lxml_5etree_adoptExternalDocument
|
19 |
+
static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_elementFactory)(struct LxmlDocument *, xmlNode *) = 0;
|
20 |
+
#define elementFactory __pyx_api_f_4lxml_5etree_elementFactory
|
21 |
+
static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_makeElement)(PyObject *, struct LxmlDocument *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *) = 0;
|
22 |
+
#define makeElement __pyx_api_f_4lxml_5etree_makeElement
|
23 |
+
static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_makeSubElement)(struct LxmlElement *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *) = 0;
|
24 |
+
#define makeSubElement __pyx_api_f_4lxml_5etree_makeSubElement
|
25 |
+
static void (*__pyx_api_f_4lxml_5etree_setElementClassLookupFunction)(_element_class_lookup_function, PyObject *) = 0;
|
26 |
+
#define setElementClassLookupFunction __pyx_api_f_4lxml_5etree_setElementClassLookupFunction
|
27 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_lookupDefaultElementClass)(PyObject *, PyObject *, xmlNode *) = 0;
|
28 |
+
#define lookupDefaultElementClass __pyx_api_f_4lxml_5etree_lookupDefaultElementClass
|
29 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_lookupNamespaceElementClass)(PyObject *, PyObject *, xmlNode *) = 0;
|
30 |
+
#define lookupNamespaceElementClass __pyx_api_f_4lxml_5etree_lookupNamespaceElementClass
|
31 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_callLookupFallback)(struct LxmlFallbackElementClassLookup *, struct LxmlDocument *, xmlNode *) = 0;
|
32 |
+
#define callLookupFallback __pyx_api_f_4lxml_5etree_callLookupFallback
|
33 |
+
static int (*__pyx_api_f_4lxml_5etree_tagMatches)(xmlNode *, const xmlChar *, const xmlChar *) = 0;
|
34 |
+
#define tagMatches __pyx_api_f_4lxml_5etree_tagMatches
|
35 |
+
static struct LxmlDocument *(*__pyx_api_f_4lxml_5etree_documentOrRaise)(PyObject *) = 0;
|
36 |
+
#define documentOrRaise __pyx_api_f_4lxml_5etree_documentOrRaise
|
37 |
+
static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_rootNodeOrRaise)(PyObject *) = 0;
|
38 |
+
#define rootNodeOrRaise __pyx_api_f_4lxml_5etree_rootNodeOrRaise
|
39 |
+
static int (*__pyx_api_f_4lxml_5etree_hasText)(xmlNode *) = 0;
|
40 |
+
#define hasText __pyx_api_f_4lxml_5etree_hasText
|
41 |
+
static int (*__pyx_api_f_4lxml_5etree_hasTail)(xmlNode *) = 0;
|
42 |
+
#define hasTail __pyx_api_f_4lxml_5etree_hasTail
|
43 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_textOf)(xmlNode *) = 0;
|
44 |
+
#define textOf __pyx_api_f_4lxml_5etree_textOf
|
45 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_tailOf)(xmlNode *) = 0;
|
46 |
+
#define tailOf __pyx_api_f_4lxml_5etree_tailOf
|
47 |
+
static int (*__pyx_api_f_4lxml_5etree_setNodeText)(xmlNode *, PyObject *) = 0;
|
48 |
+
#define setNodeText __pyx_api_f_4lxml_5etree_setNodeText
|
49 |
+
static int (*__pyx_api_f_4lxml_5etree_setTailText)(xmlNode *, PyObject *) = 0;
|
50 |
+
#define setTailText __pyx_api_f_4lxml_5etree_setTailText
|
51 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_attributeValue)(xmlNode *, xmlAttr *) = 0;
|
52 |
+
#define attributeValue __pyx_api_f_4lxml_5etree_attributeValue
|
53 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_attributeValueFromNsName)(xmlNode *, const xmlChar *, const xmlChar *) = 0;
|
54 |
+
#define attributeValueFromNsName __pyx_api_f_4lxml_5etree_attributeValueFromNsName
|
55 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_getAttributeValue)(struct LxmlElement *, PyObject *, PyObject *) = 0;
|
56 |
+
#define getAttributeValue __pyx_api_f_4lxml_5etree_getAttributeValue
|
57 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_iterattributes)(struct LxmlElement *, int) = 0;
|
58 |
+
#define iterattributes __pyx_api_f_4lxml_5etree_iterattributes
|
59 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_collectAttributes)(xmlNode *, int) = 0;
|
60 |
+
#define collectAttributes __pyx_api_f_4lxml_5etree_collectAttributes
|
61 |
+
static int (*__pyx_api_f_4lxml_5etree_setAttributeValue)(struct LxmlElement *, PyObject *, PyObject *) = 0;
|
62 |
+
#define setAttributeValue __pyx_api_f_4lxml_5etree_setAttributeValue
|
63 |
+
static int (*__pyx_api_f_4lxml_5etree_delAttribute)(struct LxmlElement *, PyObject *) = 0;
|
64 |
+
#define delAttribute __pyx_api_f_4lxml_5etree_delAttribute
|
65 |
+
static int (*__pyx_api_f_4lxml_5etree_delAttributeFromNsName)(xmlNode *, const xmlChar *, const xmlChar *) = 0;
|
66 |
+
#define delAttributeFromNsName __pyx_api_f_4lxml_5etree_delAttributeFromNsName
|
67 |
+
static int (*__pyx_api_f_4lxml_5etree_hasChild)(xmlNode *) = 0;
|
68 |
+
#define hasChild __pyx_api_f_4lxml_5etree_hasChild
|
69 |
+
static xmlNode *(*__pyx_api_f_4lxml_5etree_findChild)(xmlNode *, Py_ssize_t) = 0;
|
70 |
+
#define findChild __pyx_api_f_4lxml_5etree_findChild
|
71 |
+
static xmlNode *(*__pyx_api_f_4lxml_5etree_findChildForwards)(xmlNode *, Py_ssize_t) = 0;
|
72 |
+
#define findChildForwards __pyx_api_f_4lxml_5etree_findChildForwards
|
73 |
+
static xmlNode *(*__pyx_api_f_4lxml_5etree_findChildBackwards)(xmlNode *, Py_ssize_t) = 0;
|
74 |
+
#define findChildBackwards __pyx_api_f_4lxml_5etree_findChildBackwards
|
75 |
+
static xmlNode *(*__pyx_api_f_4lxml_5etree_nextElement)(xmlNode *) = 0;
|
76 |
+
#define nextElement __pyx_api_f_4lxml_5etree_nextElement
|
77 |
+
static xmlNode *(*__pyx_api_f_4lxml_5etree_previousElement)(xmlNode *) = 0;
|
78 |
+
#define previousElement __pyx_api_f_4lxml_5etree_previousElement
|
79 |
+
static void (*__pyx_api_f_4lxml_5etree_appendChild)(struct LxmlElement *, struct LxmlElement *) = 0;
|
80 |
+
#define appendChild __pyx_api_f_4lxml_5etree_appendChild
|
81 |
+
static int (*__pyx_api_f_4lxml_5etree_appendChildToElement)(struct LxmlElement *, struct LxmlElement *) = 0;
|
82 |
+
#define appendChildToElement __pyx_api_f_4lxml_5etree_appendChildToElement
|
83 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_pyunicode)(const xmlChar *) = 0;
|
84 |
+
#define pyunicode __pyx_api_f_4lxml_5etree_pyunicode
|
85 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_utf8)(PyObject *) = 0;
|
86 |
+
#define utf8 __pyx_api_f_4lxml_5etree_utf8
|
87 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_getNsTag)(PyObject *) = 0;
|
88 |
+
#define getNsTag __pyx_api_f_4lxml_5etree_getNsTag
|
89 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs)(PyObject *) = 0;
|
90 |
+
#define getNsTagWithEmptyNs __pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs
|
91 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_namespacedName)(xmlNode *) = 0;
|
92 |
+
#define namespacedName __pyx_api_f_4lxml_5etree_namespacedName
|
93 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_namespacedNameFromNsName)(const xmlChar *, const xmlChar *) = 0;
|
94 |
+
#define namespacedNameFromNsName __pyx_api_f_4lxml_5etree_namespacedNameFromNsName
|
95 |
+
static void (*__pyx_api_f_4lxml_5etree_iteratorStoreNext)(struct LxmlElementIterator *, struct LxmlElement *) = 0;
|
96 |
+
#define iteratorStoreNext __pyx_api_f_4lxml_5etree_iteratorStoreNext
|
97 |
+
static void (*__pyx_api_f_4lxml_5etree_initTagMatch)(struct LxmlElementTagMatcher *, PyObject *) = 0;
|
98 |
+
#define initTagMatch __pyx_api_f_4lxml_5etree_initTagMatch
|
99 |
+
static xmlNs *(*__pyx_api_f_4lxml_5etree_findOrBuildNodeNsPrefix)(struct LxmlDocument *, xmlNode *, const xmlChar *, const xmlChar *) = 0;
|
100 |
+
#define findOrBuildNodeNsPrefix __pyx_api_f_4lxml_5etree_findOrBuildNodeNsPrefix
|
101 |
+
#ifndef __PYX_HAVE_RT_ImportFunction_3_0_10
|
102 |
+
#define __PYX_HAVE_RT_ImportFunction_3_0_10
|
103 |
+
static int __Pyx_ImportFunction_3_0_10(PyObject *module, const char *funcname, void (**f)(void), const char *sig) {
|
104 |
+
PyObject *d = 0;
|
105 |
+
PyObject *cobj = 0;
|
106 |
+
union {
|
107 |
+
void (*fp)(void);
|
108 |
+
void *p;
|
109 |
+
} tmp;
|
110 |
+
d = PyObject_GetAttrString(module, (char *)"__pyx_capi__");
|
111 |
+
if (!d)
|
112 |
+
goto bad;
|
113 |
+
cobj = PyDict_GetItemString(d, funcname);
|
114 |
+
if (!cobj) {
|
115 |
+
PyErr_Format(PyExc_ImportError,
|
116 |
+
"%.200s does not export expected C function %.200s",
|
117 |
+
PyModule_GetName(module), funcname);
|
118 |
+
goto bad;
|
119 |
+
}
|
120 |
+
if (!PyCapsule_IsValid(cobj, sig)) {
|
121 |
+
PyErr_Format(PyExc_TypeError,
|
122 |
+
"C function %.200s.%.200s has wrong signature (expected %.500s, got %.500s)",
|
123 |
+
PyModule_GetName(module), funcname, sig, PyCapsule_GetName(cobj));
|
124 |
+
goto bad;
|
125 |
+
}
|
126 |
+
tmp.p = PyCapsule_GetPointer(cobj, sig);
|
127 |
+
*f = tmp.fp;
|
128 |
+
if (!(*f))
|
129 |
+
goto bad;
|
130 |
+
Py_DECREF(d);
|
131 |
+
return 0;
|
132 |
+
bad:
|
133 |
+
Py_XDECREF(d);
|
134 |
+
return -1;
|
135 |
+
}
|
136 |
+
#endif
|
137 |
+
|
138 |
+
|
139 |
+
static int import_lxml__etree(void) {
|
140 |
+
PyObject *module = 0;
|
141 |
+
module = PyImport_ImportModule("lxml.etree");
|
142 |
+
if (!module) goto bad;
|
143 |
+
if (__Pyx_ImportFunction_3_0_10(module, "deepcopyNodeToDocument", (void (**)(void))&__pyx_api_f_4lxml_5etree_deepcopyNodeToDocument, "struct LxmlElement *(struct LxmlDocument *, xmlNode *)") < 0) goto bad;
|
144 |
+
if (__Pyx_ImportFunction_3_0_10(module, "elementTreeFactory", (void (**)(void))&__pyx_api_f_4lxml_5etree_elementTreeFactory, "struct LxmlElementTree *(struct LxmlElement *)") < 0) goto bad;
|
145 |
+
if (__Pyx_ImportFunction_3_0_10(module, "newElementTree", (void (**)(void))&__pyx_api_f_4lxml_5etree_newElementTree, "struct LxmlElementTree *(struct LxmlElement *, PyObject *)") < 0) goto bad;
|
146 |
+
if (__Pyx_ImportFunction_3_0_10(module, "adoptExternalDocument", (void (**)(void))&__pyx_api_f_4lxml_5etree_adoptExternalDocument, "struct LxmlElementTree *(xmlDoc *, PyObject *, int)") < 0) goto bad;
|
147 |
+
if (__Pyx_ImportFunction_3_0_10(module, "elementFactory", (void (**)(void))&__pyx_api_f_4lxml_5etree_elementFactory, "struct LxmlElement *(struct LxmlDocument *, xmlNode *)") < 0) goto bad;
|
148 |
+
if (__Pyx_ImportFunction_3_0_10(module, "makeElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_makeElement, "struct LxmlElement *(PyObject *, struct LxmlDocument *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *)") < 0) goto bad;
|
149 |
+
if (__Pyx_ImportFunction_3_0_10(module, "makeSubElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_makeSubElement, "struct LxmlElement *(struct LxmlElement *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *)") < 0) goto bad;
|
150 |
+
if (__Pyx_ImportFunction_3_0_10(module, "setElementClassLookupFunction", (void (**)(void))&__pyx_api_f_4lxml_5etree_setElementClassLookupFunction, "void (_element_class_lookup_function, PyObject *)") < 0) goto bad;
|
151 |
+
if (__Pyx_ImportFunction_3_0_10(module, "lookupDefaultElementClass", (void (**)(void))&__pyx_api_f_4lxml_5etree_lookupDefaultElementClass, "PyObject *(PyObject *, PyObject *, xmlNode *)") < 0) goto bad;
|
152 |
+
if (__Pyx_ImportFunction_3_0_10(module, "lookupNamespaceElementClass", (void (**)(void))&__pyx_api_f_4lxml_5etree_lookupNamespaceElementClass, "PyObject *(PyObject *, PyObject *, xmlNode *)") < 0) goto bad;
|
153 |
+
if (__Pyx_ImportFunction_3_0_10(module, "callLookupFallback", (void (**)(void))&__pyx_api_f_4lxml_5etree_callLookupFallback, "PyObject *(struct LxmlFallbackElementClassLookup *, struct LxmlDocument *, xmlNode *)") < 0) goto bad;
|
154 |
+
if (__Pyx_ImportFunction_3_0_10(module, "tagMatches", (void (**)(void))&__pyx_api_f_4lxml_5etree_tagMatches, "int (xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad;
|
155 |
+
if (__Pyx_ImportFunction_3_0_10(module, "documentOrRaise", (void (**)(void))&__pyx_api_f_4lxml_5etree_documentOrRaise, "struct LxmlDocument *(PyObject *)") < 0) goto bad;
|
156 |
+
if (__Pyx_ImportFunction_3_0_10(module, "rootNodeOrRaise", (void (**)(void))&__pyx_api_f_4lxml_5etree_rootNodeOrRaise, "struct LxmlElement *(PyObject *)") < 0) goto bad;
|
157 |
+
if (__Pyx_ImportFunction_3_0_10(module, "hasText", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasText, "int (xmlNode *)") < 0) goto bad;
|
158 |
+
if (__Pyx_ImportFunction_3_0_10(module, "hasTail", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasTail, "int (xmlNode *)") < 0) goto bad;
|
159 |
+
if (__Pyx_ImportFunction_3_0_10(module, "textOf", (void (**)(void))&__pyx_api_f_4lxml_5etree_textOf, "PyObject *(xmlNode *)") < 0) goto bad;
|
160 |
+
if (__Pyx_ImportFunction_3_0_10(module, "tailOf", (void (**)(void))&__pyx_api_f_4lxml_5etree_tailOf, "PyObject *(xmlNode *)") < 0) goto bad;
|
161 |
+
if (__Pyx_ImportFunction_3_0_10(module, "setNodeText", (void (**)(void))&__pyx_api_f_4lxml_5etree_setNodeText, "int (xmlNode *, PyObject *)") < 0) goto bad;
|
162 |
+
if (__Pyx_ImportFunction_3_0_10(module, "setTailText", (void (**)(void))&__pyx_api_f_4lxml_5etree_setTailText, "int (xmlNode *, PyObject *)") < 0) goto bad;
|
163 |
+
if (__Pyx_ImportFunction_3_0_10(module, "attributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_attributeValue, "PyObject *(xmlNode *, xmlAttr *)") < 0) goto bad;
|
164 |
+
if (__Pyx_ImportFunction_3_0_10(module, "attributeValueFromNsName", (void (**)(void))&__pyx_api_f_4lxml_5etree_attributeValueFromNsName, "PyObject *(xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad;
|
165 |
+
if (__Pyx_ImportFunction_3_0_10(module, "getAttributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_getAttributeValue, "PyObject *(struct LxmlElement *, PyObject *, PyObject *)") < 0) goto bad;
|
166 |
+
if (__Pyx_ImportFunction_3_0_10(module, "iterattributes", (void (**)(void))&__pyx_api_f_4lxml_5etree_iterattributes, "PyObject *(struct LxmlElement *, int)") < 0) goto bad;
|
167 |
+
if (__Pyx_ImportFunction_3_0_10(module, "collectAttributes", (void (**)(void))&__pyx_api_f_4lxml_5etree_collectAttributes, "PyObject *(xmlNode *, int)") < 0) goto bad;
|
168 |
+
if (__Pyx_ImportFunction_3_0_10(module, "setAttributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_setAttributeValue, "int (struct LxmlElement *, PyObject *, PyObject *)") < 0) goto bad;
|
169 |
+
if (__Pyx_ImportFunction_3_0_10(module, "delAttribute", (void (**)(void))&__pyx_api_f_4lxml_5etree_delAttribute, "int (struct LxmlElement *, PyObject *)") < 0) goto bad;
|
170 |
+
if (__Pyx_ImportFunction_3_0_10(module, "delAttributeFromNsName", (void (**)(void))&__pyx_api_f_4lxml_5etree_delAttributeFromNsName, "int (xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad;
|
171 |
+
if (__Pyx_ImportFunction_3_0_10(module, "hasChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasChild, "int (xmlNode *)") < 0) goto bad;
|
172 |
+
if (__Pyx_ImportFunction_3_0_10(module, "findChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChild, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad;
|
173 |
+
if (__Pyx_ImportFunction_3_0_10(module, "findChildForwards", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChildForwards, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad;
|
174 |
+
if (__Pyx_ImportFunction_3_0_10(module, "findChildBackwards", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChildBackwards, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad;
|
175 |
+
if (__Pyx_ImportFunction_3_0_10(module, "nextElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_nextElement, "xmlNode *(xmlNode *)") < 0) goto bad;
|
176 |
+
if (__Pyx_ImportFunction_3_0_10(module, "previousElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_previousElement, "xmlNode *(xmlNode *)") < 0) goto bad;
|
177 |
+
if (__Pyx_ImportFunction_3_0_10(module, "appendChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_appendChild, "void (struct LxmlElement *, struct LxmlElement *)") < 0) goto bad;
|
178 |
+
if (__Pyx_ImportFunction_3_0_10(module, "appendChildToElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_appendChildToElement, "int (struct LxmlElement *, struct LxmlElement *)") < 0) goto bad;
|
179 |
+
if (__Pyx_ImportFunction_3_0_10(module, "pyunicode", (void (**)(void))&__pyx_api_f_4lxml_5etree_pyunicode, "PyObject *(const xmlChar *)") < 0) goto bad;
|
180 |
+
if (__Pyx_ImportFunction_3_0_10(module, "utf8", (void (**)(void))&__pyx_api_f_4lxml_5etree_utf8, "PyObject *(PyObject *)") < 0) goto bad;
|
181 |
+
if (__Pyx_ImportFunction_3_0_10(module, "getNsTag", (void (**)(void))&__pyx_api_f_4lxml_5etree_getNsTag, "PyObject *(PyObject *)") < 0) goto bad;
|
182 |
+
if (__Pyx_ImportFunction_3_0_10(module, "getNsTagWithEmptyNs", (void (**)(void))&__pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs, "PyObject *(PyObject *)") < 0) goto bad;
|
183 |
+
if (__Pyx_ImportFunction_3_0_10(module, "namespacedName", (void (**)(void))&__pyx_api_f_4lxml_5etree_namespacedName, "PyObject *(xmlNode *)") < 0) goto bad;
|
184 |
+
if (__Pyx_ImportFunction_3_0_10(module, "namespacedNameFromNsName", (void (**)(void))&__pyx_api_f_4lxml_5etree_namespacedNameFromNsName, "PyObject *(const xmlChar *, const xmlChar *)") < 0) goto bad;
|
185 |
+
if (__Pyx_ImportFunction_3_0_10(module, "iteratorStoreNext", (void (**)(void))&__pyx_api_f_4lxml_5etree_iteratorStoreNext, "void (struct LxmlElementIterator *, struct LxmlElement *)") < 0) goto bad;
|
186 |
+
if (__Pyx_ImportFunction_3_0_10(module, "initTagMatch", (void (**)(void))&__pyx_api_f_4lxml_5etree_initTagMatch, "void (struct LxmlElementTagMatcher *, PyObject *)") < 0) goto bad;
|
187 |
+
if (__Pyx_ImportFunction_3_0_10(module, "findOrBuildNodeNsPrefix", (void (**)(void))&__pyx_api_f_4lxml_5etree_findOrBuildNodeNsPrefix, "xmlNs *(struct LxmlDocument *, xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad;
|
188 |
+
Py_DECREF(module); module = 0;
|
189 |
+
return 0;
|
190 |
+
bad:
|
191 |
+
Py_XDECREF(module);
|
192 |
+
return -1;
|
193 |
+
}
|
194 |
+
|
195 |
+
#endif /* !__PYX_HAVE_API__lxml__etree */
|
llmeval-env/lib/python3.10/site-packages/lxml/html/__pycache__/_diffcommand.cpython-310.pyc
ADDED
Binary file (2.26 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/lxml/html/__pycache__/_setmixin.cpython-310.pyc
ADDED
Binary file (2.1 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/lxml/html/__pycache__/builder.cpython-310.pyc
ADDED
Binary file (2.95 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/lxml/html/__pycache__/diff.cpython-310.pyc
ADDED
Binary file (24 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/lxml/html/__pycache__/soupparser.cpython-310.pyc
ADDED
Binary file (8.02 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/lxml/html/_html5builder.py
ADDED
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Legacy module - don't use in new code!
|
3 |
+
|
4 |
+
html5lib now has its own proper implementation.
|
5 |
+
|
6 |
+
This module implements a tree builder for html5lib that generates lxml
|
7 |
+
html element trees. This module uses camelCase as it follows the
|
8 |
+
html5lib style guide.
|
9 |
+
"""
|
10 |
+
|
11 |
+
from html5lib.treebuilders import _base, etree as etree_builders
|
12 |
+
from lxml import html, etree
|
13 |
+
|
14 |
+
|
15 |
+
class DocumentType:
|
16 |
+
|
17 |
+
def __init__(self, name, publicId, systemId):
|
18 |
+
self.name = name
|
19 |
+
self.publicId = publicId
|
20 |
+
self.systemId = systemId
|
21 |
+
|
22 |
+
class Document:
|
23 |
+
|
24 |
+
def __init__(self):
|
25 |
+
self._elementTree = None
|
26 |
+
self.childNodes = []
|
27 |
+
|
28 |
+
def appendChild(self, element):
|
29 |
+
self._elementTree.getroot().addnext(element._element)
|
30 |
+
|
31 |
+
|
32 |
+
class TreeBuilder(_base.TreeBuilder):
|
33 |
+
documentClass = Document
|
34 |
+
doctypeClass = DocumentType
|
35 |
+
elementClass = None
|
36 |
+
commentClass = None
|
37 |
+
fragmentClass = Document
|
38 |
+
|
39 |
+
def __init__(self, *args, **kwargs):
|
40 |
+
html_builder = etree_builders.getETreeModule(html, fullTree=False)
|
41 |
+
etree_builder = etree_builders.getETreeModule(etree, fullTree=False)
|
42 |
+
self.elementClass = html_builder.Element
|
43 |
+
self.commentClass = etree_builder.Comment
|
44 |
+
_base.TreeBuilder.__init__(self, *args, **kwargs)
|
45 |
+
|
46 |
+
def reset(self):
|
47 |
+
_base.TreeBuilder.reset(self)
|
48 |
+
self.rootInserted = False
|
49 |
+
self.initialComments = []
|
50 |
+
self.doctype = None
|
51 |
+
|
52 |
+
def getDocument(self):
|
53 |
+
return self.document._elementTree
|
54 |
+
|
55 |
+
def getFragment(self):
|
56 |
+
fragment = []
|
57 |
+
element = self.openElements[0]._element
|
58 |
+
if element.text:
|
59 |
+
fragment.append(element.text)
|
60 |
+
fragment.extend(element.getchildren())
|
61 |
+
if element.tail:
|
62 |
+
fragment.append(element.tail)
|
63 |
+
return fragment
|
64 |
+
|
65 |
+
def insertDoctype(self, name, publicId, systemId):
|
66 |
+
doctype = self.doctypeClass(name, publicId, systemId)
|
67 |
+
self.doctype = doctype
|
68 |
+
|
69 |
+
def insertComment(self, data, parent=None):
|
70 |
+
if not self.rootInserted:
|
71 |
+
self.initialComments.append(data)
|
72 |
+
else:
|
73 |
+
_base.TreeBuilder.insertComment(self, data, parent)
|
74 |
+
|
75 |
+
def insertRoot(self, name):
|
76 |
+
buf = []
|
77 |
+
if self.doctype and self.doctype.name:
|
78 |
+
buf.append('<!DOCTYPE %s' % self.doctype.name)
|
79 |
+
if self.doctype.publicId is not None or self.doctype.systemId is not None:
|
80 |
+
buf.append(' PUBLIC "%s" "%s"' % (self.doctype.publicId,
|
81 |
+
self.doctype.systemId))
|
82 |
+
buf.append('>')
|
83 |
+
buf.append('<html></html>')
|
84 |
+
root = html.fromstring(''.join(buf))
|
85 |
+
|
86 |
+
# Append the initial comments:
|
87 |
+
for comment in self.initialComments:
|
88 |
+
root.addprevious(etree.Comment(comment))
|
89 |
+
|
90 |
+
# Create the root document and add the ElementTree to it
|
91 |
+
self.document = self.documentClass()
|
92 |
+
self.document._elementTree = root.getroottree()
|
93 |
+
|
94 |
+
# Add the root element to the internal child/open data structures
|
95 |
+
root_element = self.elementClass(name)
|
96 |
+
root_element._element = root
|
97 |
+
self.document.childNodes.append(root_element)
|
98 |
+
self.openElements.append(root_element)
|
99 |
+
|
100 |
+
self.rootInserted = True
|
llmeval-env/lib/python3.10/site-packages/lxml/html/clean.py
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# cython: language_level=3str
|
2 |
+
|
3 |
+
"""Backward-compatibility module for lxml_html_clean"""
|
4 |
+
|
5 |
+
try:
|
6 |
+
from lxml_html_clean import *
|
7 |
+
|
8 |
+
__all__ = [
|
9 |
+
"clean_html",
|
10 |
+
"clean",
|
11 |
+
"Cleaner",
|
12 |
+
"autolink",
|
13 |
+
"autolink_html",
|
14 |
+
"word_break",
|
15 |
+
"word_break_html",
|
16 |
+
]
|
17 |
+
except ImportError:
|
18 |
+
raise ImportError(
|
19 |
+
"lxml.html.clean module is now a separate project lxml_html_clean.\n"
|
20 |
+
"Install lxml[html_clean] or lxml_html_clean directly."
|
21 |
+
) from None
|
llmeval-env/lib/python3.10/site-packages/lxml/html/diff.cpython-310-x86_64-linux-gnu.so
ADDED
Binary file (373 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/lxml/html/html5parser.py
ADDED
@@ -0,0 +1,260 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
An interface to html5lib that mimics the lxml.html interface.
|
3 |
+
"""
|
4 |
+
import sys
|
5 |
+
import string
|
6 |
+
|
7 |
+
from html5lib import HTMLParser as _HTMLParser
|
8 |
+
from html5lib.treebuilders.etree_lxml import TreeBuilder
|
9 |
+
from lxml import etree
|
10 |
+
from lxml.html import Element, XHTML_NAMESPACE, _contains_block_level_tag
|
11 |
+
|
12 |
+
# python3 compatibility
|
13 |
+
try:
|
14 |
+
_strings = basestring
|
15 |
+
except NameError:
|
16 |
+
_strings = (bytes, str)
|
17 |
+
try:
|
18 |
+
from urllib2 import urlopen
|
19 |
+
except ImportError:
|
20 |
+
from urllib.request import urlopen
|
21 |
+
try:
|
22 |
+
from urlparse import urlparse
|
23 |
+
except ImportError:
|
24 |
+
from urllib.parse import urlparse
|
25 |
+
|
26 |
+
|
27 |
+
class HTMLParser(_HTMLParser):
|
28 |
+
"""An html5lib HTML parser with lxml as tree."""
|
29 |
+
|
30 |
+
def __init__(self, strict=False, **kwargs):
|
31 |
+
_HTMLParser.__init__(self, strict=strict, tree=TreeBuilder, **kwargs)
|
32 |
+
|
33 |
+
|
34 |
+
try:
|
35 |
+
from html5lib import XHTMLParser as _XHTMLParser
|
36 |
+
except ImportError:
|
37 |
+
pass
|
38 |
+
else:
|
39 |
+
class XHTMLParser(_XHTMLParser):
|
40 |
+
"""An html5lib XHTML Parser with lxml as tree."""
|
41 |
+
|
42 |
+
def __init__(self, strict=False, **kwargs):
|
43 |
+
_XHTMLParser.__init__(self, strict=strict, tree=TreeBuilder, **kwargs)
|
44 |
+
|
45 |
+
xhtml_parser = XHTMLParser()
|
46 |
+
|
47 |
+
|
48 |
+
def _find_tag(tree, tag):
|
49 |
+
elem = tree.find(tag)
|
50 |
+
if elem is not None:
|
51 |
+
return elem
|
52 |
+
return tree.find('{%s}%s' % (XHTML_NAMESPACE, tag))
|
53 |
+
|
54 |
+
|
55 |
+
def document_fromstring(html, guess_charset=None, parser=None):
|
56 |
+
"""
|
57 |
+
Parse a whole document into a string.
|
58 |
+
|
59 |
+
If `guess_charset` is true, or if the input is not Unicode but a
|
60 |
+
byte string, the `chardet` library will perform charset guessing
|
61 |
+
on the string.
|
62 |
+
"""
|
63 |
+
if not isinstance(html, _strings):
|
64 |
+
raise TypeError('string required')
|
65 |
+
|
66 |
+
if parser is None:
|
67 |
+
parser = html_parser
|
68 |
+
|
69 |
+
options = {}
|
70 |
+
if guess_charset is None and isinstance(html, bytes):
|
71 |
+
# html5lib does not accept useChardet as an argument, if it
|
72 |
+
# detected the html argument would produce unicode objects.
|
73 |
+
guess_charset = True
|
74 |
+
if guess_charset is not None:
|
75 |
+
options['useChardet'] = guess_charset
|
76 |
+
return parser.parse(html, **options).getroot()
|
77 |
+
|
78 |
+
|
79 |
+
def fragments_fromstring(html, no_leading_text=False,
|
80 |
+
guess_charset=None, parser=None):
|
81 |
+
"""Parses several HTML elements, returning a list of elements.
|
82 |
+
|
83 |
+
The first item in the list may be a string. If no_leading_text is true,
|
84 |
+
then it will be an error if there is leading text, and it will always be
|
85 |
+
a list of only elements.
|
86 |
+
|
87 |
+
If `guess_charset` is true, the `chardet` library will perform charset
|
88 |
+
guessing on the string.
|
89 |
+
"""
|
90 |
+
if not isinstance(html, _strings):
|
91 |
+
raise TypeError('string required')
|
92 |
+
|
93 |
+
if parser is None:
|
94 |
+
parser = html_parser
|
95 |
+
|
96 |
+
options = {}
|
97 |
+
if guess_charset is None and isinstance(html, bytes):
|
98 |
+
# html5lib does not accept useChardet as an argument, if it
|
99 |
+
# detected the html argument would produce unicode objects.
|
100 |
+
guess_charset = False
|
101 |
+
if guess_charset is not None:
|
102 |
+
options['useChardet'] = guess_charset
|
103 |
+
children = parser.parseFragment(html, 'div', **options)
|
104 |
+
if children and isinstance(children[0], _strings):
|
105 |
+
if no_leading_text:
|
106 |
+
if children[0].strip():
|
107 |
+
raise etree.ParserError('There is leading text: %r' %
|
108 |
+
children[0])
|
109 |
+
del children[0]
|
110 |
+
return children
|
111 |
+
|
112 |
+
|
113 |
+
def fragment_fromstring(html, create_parent=False,
|
114 |
+
guess_charset=None, parser=None):
|
115 |
+
"""Parses a single HTML element; it is an error if there is more than
|
116 |
+
one element, or if anything but whitespace precedes or follows the
|
117 |
+
element.
|
118 |
+
|
119 |
+
If 'create_parent' is true (or is a tag name) then a parent node
|
120 |
+
will be created to encapsulate the HTML in a single element. In
|
121 |
+
this case, leading or trailing text is allowed.
|
122 |
+
|
123 |
+
If `guess_charset` is true, the `chardet` library will perform charset
|
124 |
+
guessing on the string.
|
125 |
+
"""
|
126 |
+
if not isinstance(html, _strings):
|
127 |
+
raise TypeError('string required')
|
128 |
+
|
129 |
+
accept_leading_text = bool(create_parent)
|
130 |
+
|
131 |
+
elements = fragments_fromstring(
|
132 |
+
html, guess_charset=guess_charset, parser=parser,
|
133 |
+
no_leading_text=not accept_leading_text)
|
134 |
+
|
135 |
+
if create_parent:
|
136 |
+
if not isinstance(create_parent, _strings):
|
137 |
+
create_parent = 'div'
|
138 |
+
new_root = Element(create_parent)
|
139 |
+
if elements:
|
140 |
+
if isinstance(elements[0], _strings):
|
141 |
+
new_root.text = elements[0]
|
142 |
+
del elements[0]
|
143 |
+
new_root.extend(elements)
|
144 |
+
return new_root
|
145 |
+
|
146 |
+
if not elements:
|
147 |
+
raise etree.ParserError('No elements found')
|
148 |
+
if len(elements) > 1:
|
149 |
+
raise etree.ParserError('Multiple elements found')
|
150 |
+
result = elements[0]
|
151 |
+
if result.tail and result.tail.strip():
|
152 |
+
raise etree.ParserError('Element followed by text: %r' % result.tail)
|
153 |
+
result.tail = None
|
154 |
+
return result
|
155 |
+
|
156 |
+
|
157 |
+
def fromstring(html, guess_charset=None, parser=None):
|
158 |
+
"""Parse the html, returning a single element/document.
|
159 |
+
|
160 |
+
This tries to minimally parse the chunk of text, without knowing if it
|
161 |
+
is a fragment or a document.
|
162 |
+
|
163 |
+
'base_url' will set the document's base_url attribute (and the tree's
|
164 |
+
docinfo.URL)
|
165 |
+
|
166 |
+
If `guess_charset` is true, or if the input is not Unicode but a
|
167 |
+
byte string, the `chardet` library will perform charset guessing
|
168 |
+
on the string.
|
169 |
+
"""
|
170 |
+
if not isinstance(html, _strings):
|
171 |
+
raise TypeError('string required')
|
172 |
+
doc = document_fromstring(html, parser=parser,
|
173 |
+
guess_charset=guess_charset)
|
174 |
+
|
175 |
+
# document starts with doctype or <html>, full document!
|
176 |
+
start = html[:50]
|
177 |
+
if isinstance(start, bytes):
|
178 |
+
# Allow text comparison in python3.
|
179 |
+
# Decode as ascii, that also covers latin-1 and utf-8 for the
|
180 |
+
# characters we need.
|
181 |
+
start = start.decode('ascii', 'replace')
|
182 |
+
|
183 |
+
start = start.lstrip().lower()
|
184 |
+
if start.startswith('<html') or start.startswith('<!doctype'):
|
185 |
+
return doc
|
186 |
+
|
187 |
+
head = _find_tag(doc, 'head')
|
188 |
+
|
189 |
+
# if the head is not empty we have a full document
|
190 |
+
if len(head):
|
191 |
+
return doc
|
192 |
+
|
193 |
+
body = _find_tag(doc, 'body')
|
194 |
+
|
195 |
+
# The body has just one element, so it was probably a single
|
196 |
+
# element passed in
|
197 |
+
if (len(body) == 1 and (not body.text or not body.text.strip())
|
198 |
+
and (not body[-1].tail or not body[-1].tail.strip())):
|
199 |
+
return body[0]
|
200 |
+
|
201 |
+
# Now we have a body which represents a bunch of tags which have the
|
202 |
+
# content that was passed in. We will create a fake container, which
|
203 |
+
# is the body tag, except <body> implies too much structure.
|
204 |
+
if _contains_block_level_tag(body):
|
205 |
+
body.tag = 'div'
|
206 |
+
else:
|
207 |
+
body.tag = 'span'
|
208 |
+
return body
|
209 |
+
|
210 |
+
|
211 |
+
def parse(filename_url_or_file, guess_charset=None, parser=None):
|
212 |
+
"""Parse a filename, URL, or file-like object into an HTML document
|
213 |
+
tree. Note: this returns a tree, not an element. Use
|
214 |
+
``parse(...).getroot()`` to get the document root.
|
215 |
+
|
216 |
+
If ``guess_charset`` is true, the ``useChardet`` option is passed into
|
217 |
+
html5lib to enable character detection. This option is on by default
|
218 |
+
when parsing from URLs, off by default when parsing from file(-like)
|
219 |
+
objects (which tend to return Unicode more often than not), and on by
|
220 |
+
default when parsing from a file path (which is read in binary mode).
|
221 |
+
"""
|
222 |
+
if parser is None:
|
223 |
+
parser = html_parser
|
224 |
+
if not isinstance(filename_url_or_file, _strings):
|
225 |
+
fp = filename_url_or_file
|
226 |
+
if guess_charset is None:
|
227 |
+
# assume that file-like objects return Unicode more often than bytes
|
228 |
+
guess_charset = False
|
229 |
+
elif _looks_like_url(filename_url_or_file):
|
230 |
+
fp = urlopen(filename_url_or_file)
|
231 |
+
if guess_charset is None:
|
232 |
+
# assume that URLs return bytes
|
233 |
+
guess_charset = True
|
234 |
+
else:
|
235 |
+
fp = open(filename_url_or_file, 'rb')
|
236 |
+
if guess_charset is None:
|
237 |
+
guess_charset = True
|
238 |
+
|
239 |
+
options = {}
|
240 |
+
# html5lib does not accept useChardet as an argument, if it
|
241 |
+
# detected the html argument would produce unicode objects.
|
242 |
+
if guess_charset:
|
243 |
+
options['useChardet'] = guess_charset
|
244 |
+
return parser.parse(fp, **options)
|
245 |
+
|
246 |
+
|
247 |
+
def _looks_like_url(str):
|
248 |
+
scheme = urlparse(str)[0]
|
249 |
+
if not scheme:
|
250 |
+
return False
|
251 |
+
elif (sys.platform == 'win32' and
|
252 |
+
scheme in string.ascii_letters
|
253 |
+
and len(scheme) == 1):
|
254 |
+
# looks like a 'normal' absolute path
|
255 |
+
return False
|
256 |
+
else:
|
257 |
+
return True
|
258 |
+
|
259 |
+
|
260 |
+
html_parser = HTMLParser()
|
llmeval-env/lib/python3.10/site-packages/lxml/html/soupparser.py
ADDED
@@ -0,0 +1,314 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""External interface to the BeautifulSoup HTML parser.
|
2 |
+
"""
|
3 |
+
|
4 |
+
__all__ = ["fromstring", "parse", "convert_tree"]
|
5 |
+
|
6 |
+
import re
|
7 |
+
from lxml import etree, html
|
8 |
+
|
9 |
+
try:
|
10 |
+
from bs4 import (
|
11 |
+
BeautifulSoup, Tag, Comment, ProcessingInstruction, NavigableString,
|
12 |
+
Declaration, Doctype)
|
13 |
+
_DECLARATION_OR_DOCTYPE = (Declaration, Doctype)
|
14 |
+
except ImportError:
|
15 |
+
from BeautifulSoup import (
|
16 |
+
BeautifulSoup, Tag, Comment, ProcessingInstruction, NavigableString,
|
17 |
+
Declaration)
|
18 |
+
_DECLARATION_OR_DOCTYPE = Declaration
|
19 |
+
|
20 |
+
|
21 |
+
def fromstring(data, beautifulsoup=None, makeelement=None, **bsargs):
|
22 |
+
"""Parse a string of HTML data into an Element tree using the
|
23 |
+
BeautifulSoup parser.
|
24 |
+
|
25 |
+
Returns the root ``<html>`` Element of the tree.
|
26 |
+
|
27 |
+
You can pass a different BeautifulSoup parser through the
|
28 |
+
`beautifulsoup` keyword, and a diffent Element factory function
|
29 |
+
through the `makeelement` keyword. By default, the standard
|
30 |
+
``BeautifulSoup`` class and the default factory of `lxml.html` are
|
31 |
+
used.
|
32 |
+
"""
|
33 |
+
return _parse(data, beautifulsoup, makeelement, **bsargs)
|
34 |
+
|
35 |
+
|
36 |
+
def parse(file, beautifulsoup=None, makeelement=None, **bsargs):
|
37 |
+
"""Parse a file into an ElemenTree using the BeautifulSoup parser.
|
38 |
+
|
39 |
+
You can pass a different BeautifulSoup parser through the
|
40 |
+
`beautifulsoup` keyword, and a diffent Element factory function
|
41 |
+
through the `makeelement` keyword. By default, the standard
|
42 |
+
``BeautifulSoup`` class and the default factory of `lxml.html` are
|
43 |
+
used.
|
44 |
+
"""
|
45 |
+
if not hasattr(file, 'read'):
|
46 |
+
file = open(file)
|
47 |
+
root = _parse(file, beautifulsoup, makeelement, **bsargs)
|
48 |
+
return etree.ElementTree(root)
|
49 |
+
|
50 |
+
|
51 |
+
def convert_tree(beautiful_soup_tree, makeelement=None):
|
52 |
+
"""Convert a BeautifulSoup tree to a list of Element trees.
|
53 |
+
|
54 |
+
Returns a list instead of a single root Element to support
|
55 |
+
HTML-like soup with more than one root element.
|
56 |
+
|
57 |
+
You can pass a different Element factory through the `makeelement`
|
58 |
+
keyword.
|
59 |
+
"""
|
60 |
+
root = _convert_tree(beautiful_soup_tree, makeelement)
|
61 |
+
children = root.getchildren()
|
62 |
+
for child in children:
|
63 |
+
root.remove(child)
|
64 |
+
return children
|
65 |
+
|
66 |
+
|
67 |
+
# helpers
|
68 |
+
|
69 |
+
def _parse(source, beautifulsoup, makeelement, **bsargs):
|
70 |
+
if beautifulsoup is None:
|
71 |
+
beautifulsoup = BeautifulSoup
|
72 |
+
if hasattr(beautifulsoup, "HTML_ENTITIES"): # bs3
|
73 |
+
if 'convertEntities' not in bsargs:
|
74 |
+
bsargs['convertEntities'] = 'html'
|
75 |
+
if hasattr(beautifulsoup, "DEFAULT_BUILDER_FEATURES"): # bs4
|
76 |
+
if 'features' not in bsargs:
|
77 |
+
bsargs['features'] = 'html.parser' # use Python html parser
|
78 |
+
tree = beautifulsoup(source, **bsargs)
|
79 |
+
root = _convert_tree(tree, makeelement)
|
80 |
+
# from ET: wrap the document in a html root element, if necessary
|
81 |
+
if len(root) == 1 and root[0].tag == "html":
|
82 |
+
return root[0]
|
83 |
+
root.tag = "html"
|
84 |
+
return root
|
85 |
+
|
86 |
+
|
87 |
+
_parse_doctype_declaration = re.compile(
|
88 |
+
r'(?:\s|[<!])*DOCTYPE\s*HTML'
|
89 |
+
r'(?:\s+PUBLIC)?(?:\s+(\'[^\']*\'|"[^"]*"))?'
|
90 |
+
r'(?:\s+(\'[^\']*\'|"[^"]*"))?',
|
91 |
+
re.IGNORECASE).match
|
92 |
+
|
93 |
+
|
94 |
+
class _PseudoTag:
|
95 |
+
# Minimal imitation of BeautifulSoup.Tag
|
96 |
+
def __init__(self, contents):
|
97 |
+
self.name = 'html'
|
98 |
+
self.attrs = []
|
99 |
+
self.contents = contents
|
100 |
+
|
101 |
+
def __iter__(self):
|
102 |
+
return self.contents.__iter__()
|
103 |
+
|
104 |
+
|
105 |
+
def _convert_tree(beautiful_soup_tree, makeelement):
|
106 |
+
if makeelement is None:
|
107 |
+
makeelement = html.html_parser.makeelement
|
108 |
+
|
109 |
+
# Split the tree into three parts:
|
110 |
+
# i) everything before the root element: document type
|
111 |
+
# declaration, comments, processing instructions, whitespace
|
112 |
+
# ii) the root(s),
|
113 |
+
# iii) everything after the root: comments, processing
|
114 |
+
# instructions, whitespace
|
115 |
+
first_element_idx = last_element_idx = None
|
116 |
+
html_root = declaration = None
|
117 |
+
for i, e in enumerate(beautiful_soup_tree):
|
118 |
+
if isinstance(e, Tag):
|
119 |
+
if first_element_idx is None:
|
120 |
+
first_element_idx = i
|
121 |
+
last_element_idx = i
|
122 |
+
if html_root is None and e.name and e.name.lower() == 'html':
|
123 |
+
html_root = e
|
124 |
+
elif declaration is None and isinstance(e, _DECLARATION_OR_DOCTYPE):
|
125 |
+
declaration = e
|
126 |
+
|
127 |
+
# For a nice, well-formatted document, the variable roots below is
|
128 |
+
# a list consisting of a single <html> element. However, the document
|
129 |
+
# may be a soup like '<meta><head><title>Hello</head><body>Hi
|
130 |
+
# all<\p>'. In this example roots is a list containing meta, head
|
131 |
+
# and body elements.
|
132 |
+
if first_element_idx is None:
|
133 |
+
pre_root = post_root = []
|
134 |
+
roots = beautiful_soup_tree.contents
|
135 |
+
else:
|
136 |
+
pre_root = beautiful_soup_tree.contents[:first_element_idx]
|
137 |
+
roots = beautiful_soup_tree.contents[first_element_idx:last_element_idx+1]
|
138 |
+
post_root = beautiful_soup_tree.contents[last_element_idx+1:]
|
139 |
+
|
140 |
+
# Reorganize so that there is one <html> root...
|
141 |
+
if html_root is not None:
|
142 |
+
# ... use existing one if possible, ...
|
143 |
+
i = roots.index(html_root)
|
144 |
+
html_root.contents = roots[:i] + html_root.contents + roots[i+1:]
|
145 |
+
else:
|
146 |
+
# ... otherwise create a new one.
|
147 |
+
html_root = _PseudoTag(roots)
|
148 |
+
|
149 |
+
convert_node = _init_node_converters(makeelement)
|
150 |
+
|
151 |
+
# Process pre_root
|
152 |
+
res_root = convert_node(html_root)
|
153 |
+
prev = res_root
|
154 |
+
for e in reversed(pre_root):
|
155 |
+
converted = convert_node(e)
|
156 |
+
if converted is not None:
|
157 |
+
prev.addprevious(converted)
|
158 |
+
prev = converted
|
159 |
+
|
160 |
+
# ditto for post_root
|
161 |
+
prev = res_root
|
162 |
+
for e in post_root:
|
163 |
+
converted = convert_node(e)
|
164 |
+
if converted is not None:
|
165 |
+
prev.addnext(converted)
|
166 |
+
prev = converted
|
167 |
+
|
168 |
+
if declaration is not None:
|
169 |
+
try:
|
170 |
+
# bs4 provides full Doctype string
|
171 |
+
doctype_string = declaration.output_ready()
|
172 |
+
except AttributeError:
|
173 |
+
doctype_string = declaration.string
|
174 |
+
|
175 |
+
match = _parse_doctype_declaration(doctype_string)
|
176 |
+
if not match:
|
177 |
+
# Something is wrong if we end up in here. Since soupparser should
|
178 |
+
# tolerate errors, do not raise Exception, just let it pass.
|
179 |
+
pass
|
180 |
+
else:
|
181 |
+
external_id, sys_uri = match.groups()
|
182 |
+
docinfo = res_root.getroottree().docinfo
|
183 |
+
# strip quotes and update DOCTYPE values (any of None, '', '...')
|
184 |
+
docinfo.public_id = external_id and external_id[1:-1]
|
185 |
+
docinfo.system_url = sys_uri and sys_uri[1:-1]
|
186 |
+
|
187 |
+
return res_root
|
188 |
+
|
189 |
+
|
190 |
+
def _init_node_converters(makeelement):
|
191 |
+
converters = {}
|
192 |
+
ordered_node_types = []
|
193 |
+
|
194 |
+
def converter(*types):
|
195 |
+
def add(handler):
|
196 |
+
for t in types:
|
197 |
+
converters[t] = handler
|
198 |
+
ordered_node_types.append(t)
|
199 |
+
return handler
|
200 |
+
return add
|
201 |
+
|
202 |
+
def find_best_converter(node):
|
203 |
+
for t in ordered_node_types:
|
204 |
+
if isinstance(node, t):
|
205 |
+
return converters[t]
|
206 |
+
return None
|
207 |
+
|
208 |
+
def convert_node(bs_node, parent=None):
|
209 |
+
# duplicated in convert_tag() below
|
210 |
+
try:
|
211 |
+
handler = converters[type(bs_node)]
|
212 |
+
except KeyError:
|
213 |
+
handler = converters[type(bs_node)] = find_best_converter(bs_node)
|
214 |
+
if handler is None:
|
215 |
+
return None
|
216 |
+
return handler(bs_node, parent)
|
217 |
+
|
218 |
+
def map_attrs(bs_attrs):
|
219 |
+
if isinstance(bs_attrs, dict): # bs4
|
220 |
+
attribs = {}
|
221 |
+
for k, v in bs_attrs.items():
|
222 |
+
if isinstance(v, list):
|
223 |
+
v = " ".join(v)
|
224 |
+
attribs[k] = unescape(v)
|
225 |
+
else:
|
226 |
+
attribs = {k: unescape(v) for k, v in bs_attrs}
|
227 |
+
return attribs
|
228 |
+
|
229 |
+
def append_text(parent, text):
|
230 |
+
if len(parent) == 0:
|
231 |
+
parent.text = (parent.text or '') + text
|
232 |
+
else:
|
233 |
+
parent[-1].tail = (parent[-1].tail or '') + text
|
234 |
+
|
235 |
+
# converters are tried in order of their definition
|
236 |
+
|
237 |
+
@converter(Tag, _PseudoTag)
|
238 |
+
def convert_tag(bs_node, parent):
|
239 |
+
attrs = bs_node.attrs
|
240 |
+
if parent is not None:
|
241 |
+
attribs = map_attrs(attrs) if attrs else None
|
242 |
+
res = etree.SubElement(parent, bs_node.name, attrib=attribs)
|
243 |
+
else:
|
244 |
+
attribs = map_attrs(attrs) if attrs else {}
|
245 |
+
res = makeelement(bs_node.name, attrib=attribs)
|
246 |
+
|
247 |
+
for child in bs_node:
|
248 |
+
# avoid double recursion by inlining convert_node(), see above
|
249 |
+
try:
|
250 |
+
handler = converters[type(child)]
|
251 |
+
except KeyError:
|
252 |
+
pass
|
253 |
+
else:
|
254 |
+
if handler is not None:
|
255 |
+
handler(child, res)
|
256 |
+
continue
|
257 |
+
convert_node(child, res)
|
258 |
+
return res
|
259 |
+
|
260 |
+
@converter(Comment)
|
261 |
+
def convert_comment(bs_node, parent):
|
262 |
+
res = html.HtmlComment(bs_node)
|
263 |
+
if parent is not None:
|
264 |
+
parent.append(res)
|
265 |
+
return res
|
266 |
+
|
267 |
+
@converter(ProcessingInstruction)
|
268 |
+
def convert_pi(bs_node, parent):
|
269 |
+
if bs_node.endswith('?'):
|
270 |
+
# The PI is of XML style (<?as df?>) but BeautifulSoup
|
271 |
+
# interpreted it as being SGML style (<?as df>). Fix.
|
272 |
+
bs_node = bs_node[:-1]
|
273 |
+
res = etree.ProcessingInstruction(*bs_node.split(' ', 1))
|
274 |
+
if parent is not None:
|
275 |
+
parent.append(res)
|
276 |
+
return res
|
277 |
+
|
278 |
+
@converter(NavigableString)
|
279 |
+
def convert_text(bs_node, parent):
|
280 |
+
if parent is not None:
|
281 |
+
append_text(parent, unescape(bs_node))
|
282 |
+
return None
|
283 |
+
|
284 |
+
return convert_node
|
285 |
+
|
286 |
+
|
287 |
+
# copied from ET's ElementSoup
|
288 |
+
|
289 |
+
try:
|
290 |
+
from html.entities import name2codepoint # Python 3
|
291 |
+
except ImportError:
|
292 |
+
from htmlentitydefs import name2codepoint
|
293 |
+
|
294 |
+
|
295 |
+
handle_entities = re.compile(r"&(\w+);").sub
|
296 |
+
|
297 |
+
|
298 |
+
try:
|
299 |
+
unichr
|
300 |
+
except NameError:
|
301 |
+
# Python 3
|
302 |
+
unichr = chr
|
303 |
+
|
304 |
+
|
305 |
+
def unescape(string):
|
306 |
+
if not string:
|
307 |
+
return ''
|
308 |
+
# work around oddities in BeautifulSoup's entity handling
|
309 |
+
def unescape_entity(m):
|
310 |
+
try:
|
311 |
+
return unichr(name2codepoint[m.group(1)])
|
312 |
+
except KeyError:
|
313 |
+
return m.group(0) # use as is
|
314 |
+
return handle_entities(unescape_entity, string)
|
llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/__init__.py
ADDED
@@ -0,0 +1,348 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""The ``lxml.isoschematron`` package implements ISO Schematron support on top
|
2 |
+
of the pure-xslt 'skeleton' implementation.
|
3 |
+
"""
|
4 |
+
|
5 |
+
import sys
|
6 |
+
import os.path
|
7 |
+
from lxml import etree as _etree # due to validator __init__ signature
|
8 |
+
|
9 |
+
|
10 |
+
# some compat stuff, borrowed from lxml.html
|
11 |
+
try:
|
12 |
+
unicode
|
13 |
+
except NameError:
|
14 |
+
# Python 3
|
15 |
+
unicode = str
|
16 |
+
try:
|
17 |
+
basestring
|
18 |
+
except NameError:
|
19 |
+
# Python 3
|
20 |
+
basestring = str
|
21 |
+
|
22 |
+
|
23 |
+
__all__ = ['extract_xsd', 'extract_rng', 'iso_dsdl_include',
|
24 |
+
'iso_abstract_expand', 'iso_svrl_for_xslt1',
|
25 |
+
'svrl_validation_errors', 'schematron_schema_valid',
|
26 |
+
'stylesheet_params', 'Schematron']
|
27 |
+
|
28 |
+
|
29 |
+
# some namespaces
|
30 |
+
#FIXME: Maybe lxml should provide a dedicated place for common namespace
|
31 |
+
#FIXME: definitions?
|
32 |
+
XML_SCHEMA_NS = "http://www.w3.org/2001/XMLSchema"
|
33 |
+
RELAXNG_NS = "http://relaxng.org/ns/structure/1.0"
|
34 |
+
SCHEMATRON_NS = "http://purl.oclc.org/dsdl/schematron"
|
35 |
+
SVRL_NS = "http://purl.oclc.org/dsdl/svrl"
|
36 |
+
|
37 |
+
|
38 |
+
# some helpers
|
39 |
+
_schematron_root = '{%s}schema' % SCHEMATRON_NS
|
40 |
+
_xml_schema_root = '{%s}schema' % XML_SCHEMA_NS
|
41 |
+
_resources_dir = os.path.join(os.path.dirname(__file__), 'resources')
|
42 |
+
|
43 |
+
|
44 |
+
# the iso-schematron skeleton implementation steps aka xsl transformations
|
45 |
+
extract_xsd = _etree.XSLT(_etree.parse(
|
46 |
+
os.path.join(_resources_dir, 'xsl', 'XSD2Schtrn.xsl')))
|
47 |
+
extract_rng = _etree.XSLT(_etree.parse(
|
48 |
+
os.path.join(_resources_dir, 'xsl', 'RNG2Schtrn.xsl')))
|
49 |
+
iso_dsdl_include = _etree.XSLT(_etree.parse(
|
50 |
+
os.path.join(_resources_dir, 'xsl', 'iso-schematron-xslt1',
|
51 |
+
'iso_dsdl_include.xsl')))
|
52 |
+
iso_abstract_expand = _etree.XSLT(_etree.parse(
|
53 |
+
os.path.join(_resources_dir, 'xsl', 'iso-schematron-xslt1',
|
54 |
+
'iso_abstract_expand.xsl')))
|
55 |
+
iso_svrl_for_xslt1 = _etree.XSLT(_etree.parse(
|
56 |
+
os.path.join(_resources_dir,
|
57 |
+
'xsl', 'iso-schematron-xslt1', 'iso_svrl_for_xslt1.xsl')))
|
58 |
+
|
59 |
+
|
60 |
+
# svrl result accessors
|
61 |
+
svrl_validation_errors = _etree.XPath(
|
62 |
+
'//svrl:failed-assert', namespaces={'svrl': SVRL_NS})
|
63 |
+
|
64 |
+
# RelaxNG validator for schematron schemas
|
65 |
+
schematron_schema_valid_supported = False
|
66 |
+
try:
|
67 |
+
schematron_schema_valid = _etree.RelaxNG(
|
68 |
+
file=os.path.join(_resources_dir, 'rng', 'iso-schematron.rng'))
|
69 |
+
schematron_schema_valid_supported = True
|
70 |
+
except _etree.RelaxNGParseError:
|
71 |
+
# Some distributions delete the file due to licensing issues.
|
72 |
+
def schematron_schema_valid(arg):
|
73 |
+
raise NotImplementedError("Validating the ISO schematron requires iso-schematron.rng")
|
74 |
+
|
75 |
+
|
76 |
+
def stylesheet_params(**kwargs):
|
77 |
+
"""Convert keyword args to a dictionary of stylesheet parameters.
|
78 |
+
XSL stylesheet parameters must be XPath expressions, i.e.:
|
79 |
+
|
80 |
+
* string expressions, like "'5'"
|
81 |
+
* simple (number) expressions, like "5"
|
82 |
+
* valid XPath expressions, like "/a/b/text()"
|
83 |
+
|
84 |
+
This function converts native Python keyword arguments to stylesheet
|
85 |
+
parameters following these rules:
|
86 |
+
If an arg is a string wrap it with XSLT.strparam().
|
87 |
+
If an arg is an XPath object use its path string.
|
88 |
+
If arg is None raise TypeError.
|
89 |
+
Else convert arg to string.
|
90 |
+
"""
|
91 |
+
result = {}
|
92 |
+
for key, val in kwargs.items():
|
93 |
+
if isinstance(val, basestring):
|
94 |
+
val = _etree.XSLT.strparam(val)
|
95 |
+
elif val is None:
|
96 |
+
raise TypeError('None not allowed as a stylesheet parameter')
|
97 |
+
elif not isinstance(val, _etree.XPath):
|
98 |
+
val = unicode(val)
|
99 |
+
result[key] = val
|
100 |
+
return result
|
101 |
+
|
102 |
+
|
103 |
+
# helper function for use in Schematron __init__
|
104 |
+
def _stylesheet_param_dict(paramsDict, kwargsDict):
|
105 |
+
"""Return a copy of paramsDict, updated with kwargsDict entries, wrapped as
|
106 |
+
stylesheet arguments.
|
107 |
+
kwargsDict entries with a value of None are ignored.
|
108 |
+
"""
|
109 |
+
# beware of changing mutable default arg
|
110 |
+
paramsDict = dict(paramsDict)
|
111 |
+
for k, v in kwargsDict.items():
|
112 |
+
if v is not None: # None values do not override
|
113 |
+
paramsDict[k] = v
|
114 |
+
paramsDict = stylesheet_params(**paramsDict)
|
115 |
+
return paramsDict
|
116 |
+
|
117 |
+
|
118 |
+
class Schematron(_etree._Validator):
|
119 |
+
"""An ISO Schematron validator.
|
120 |
+
|
121 |
+
Pass a root Element or an ElementTree to turn it into a validator.
|
122 |
+
Alternatively, pass a filename as keyword argument 'file' to parse from
|
123 |
+
the file system.
|
124 |
+
|
125 |
+
Schematron is a less well known, but very powerful schema language.
|
126 |
+
The main idea is to use the capabilities of XPath to put restrictions on
|
127 |
+
the structure and the content of XML documents.
|
128 |
+
|
129 |
+
The standard behaviour is to fail on ``failed-assert`` findings only
|
130 |
+
(``ASSERTS_ONLY``). To change this, you can either pass a report filter
|
131 |
+
function to the ``error_finder`` parameter (e.g. ``ASSERTS_AND_REPORTS``
|
132 |
+
or a custom ``XPath`` object), or subclass isoschematron.Schematron for
|
133 |
+
complete control of the validation process.
|
134 |
+
|
135 |
+
Built on the Schematron language 'reference' skeleton pure-xslt
|
136 |
+
implementation, the validator is created as an XSLT 1.0 stylesheet using
|
137 |
+
these steps:
|
138 |
+
|
139 |
+
0) (Extract from XML Schema or RelaxNG schema)
|
140 |
+
1) Process inclusions
|
141 |
+
2) Process abstract patterns
|
142 |
+
3) Compile the schematron schema to XSLT
|
143 |
+
|
144 |
+
The ``include`` and ``expand`` keyword arguments can be used to switch off
|
145 |
+
steps 1) and 2).
|
146 |
+
To set parameters for steps 1), 2) and 3) hand parameter dictionaries to the
|
147 |
+
keyword arguments ``include_params``, ``expand_params`` or
|
148 |
+
``compile_params``.
|
149 |
+
For convenience, the compile-step parameter ``phase`` is also exposed as a
|
150 |
+
keyword argument ``phase``. This takes precedence if the parameter is also
|
151 |
+
given in the parameter dictionary.
|
152 |
+
|
153 |
+
If ``store_schematron`` is set to True, the (included-and-expanded)
|
154 |
+
schematron document tree is stored and available through the ``schematron``
|
155 |
+
property.
|
156 |
+
If ``store_xslt`` is set to True, the validation XSLT document tree will be
|
157 |
+
stored and can be retrieved through the ``validator_xslt`` property.
|
158 |
+
With ``store_report`` set to True (default: False), the resulting validation
|
159 |
+
report document gets stored and can be accessed as the ``validation_report``
|
160 |
+
property.
|
161 |
+
|
162 |
+
If ``validate_schema`` is set to False, the validation of the schema file
|
163 |
+
itself is disabled. Validation happens by default after building the full
|
164 |
+
schema, unless the schema validation file cannot be found at import time,
|
165 |
+
in which case the validation gets disabled. Some lxml distributions exclude
|
166 |
+
this file due to licensing issues. ISO-Schematron validation can then still
|
167 |
+
be used normally, but the schemas themselves cannot be validated.
|
168 |
+
|
169 |
+
Here is a usage example::
|
170 |
+
|
171 |
+
>>> from lxml import etree
|
172 |
+
>>> from lxml.isoschematron import Schematron
|
173 |
+
|
174 |
+
>>> schematron = Schematron(etree.XML('''
|
175 |
+
... <schema xmlns="http://purl.oclc.org/dsdl/schematron" >
|
176 |
+
... <pattern id="id_only_attribute">
|
177 |
+
... <title>id is the only permitted attribute name</title>
|
178 |
+
... <rule context="*">
|
179 |
+
... <report test="@*[not(name()='id')]">Attribute
|
180 |
+
... <name path="@*[not(name()='id')]"/> is forbidden<name/>
|
181 |
+
... </report>
|
182 |
+
... </rule>
|
183 |
+
... </pattern>
|
184 |
+
... </schema>'''),
|
185 |
+
... error_finder=Schematron.ASSERTS_AND_REPORTS)
|
186 |
+
|
187 |
+
>>> xml = etree.XML('''
|
188 |
+
... <AAA name="aaa">
|
189 |
+
... <BBB id="bbb"/>
|
190 |
+
... <CCC color="ccc"/>
|
191 |
+
... </AAA>
|
192 |
+
... ''')
|
193 |
+
|
194 |
+
>>> schematron.validate(xml)
|
195 |
+
False
|
196 |
+
|
197 |
+
>>> xml = etree.XML('''
|
198 |
+
... <AAA id="aaa">
|
199 |
+
... <BBB id="bbb"/>
|
200 |
+
... <CCC/>
|
201 |
+
... </AAA>
|
202 |
+
... ''')
|
203 |
+
|
204 |
+
>>> schematron.validate(xml)
|
205 |
+
True
|
206 |
+
"""
|
207 |
+
|
208 |
+
# libxml2 error categorization for validation errors
|
209 |
+
_domain = _etree.ErrorDomains.SCHEMATRONV
|
210 |
+
_level = _etree.ErrorLevels.ERROR
|
211 |
+
_error_type = _etree.ErrorTypes.SCHEMATRONV_ASSERT
|
212 |
+
|
213 |
+
# convenience definitions for common behaviours
|
214 |
+
ASSERTS_ONLY = svrl_validation_errors # Default
|
215 |
+
ASSERTS_AND_REPORTS = _etree.XPath(
|
216 |
+
'//svrl:failed-assert | //svrl:successful-report',
|
217 |
+
namespaces={'svrl': SVRL_NS})
|
218 |
+
|
219 |
+
def _extract(self, element):
|
220 |
+
"""Extract embedded schematron schema from non-schematron host schema.
|
221 |
+
This method will only be called by __init__ if the given schema document
|
222 |
+
is not a schematron schema by itself.
|
223 |
+
Must return a schematron schema document tree or None.
|
224 |
+
"""
|
225 |
+
schematron = None
|
226 |
+
if element.tag == _xml_schema_root:
|
227 |
+
schematron = self._extract_xsd(element)
|
228 |
+
elif element.nsmap[element.prefix] == RELAXNG_NS:
|
229 |
+
# RelaxNG does not have a single unique root element
|
230 |
+
schematron = self._extract_rng(element)
|
231 |
+
return schematron
|
232 |
+
|
233 |
+
# customization points
|
234 |
+
# etree.XSLT objects that provide the extract, include, expand, compile
|
235 |
+
# steps
|
236 |
+
_extract_xsd = extract_xsd
|
237 |
+
_extract_rng = extract_rng
|
238 |
+
_include = iso_dsdl_include
|
239 |
+
_expand = iso_abstract_expand
|
240 |
+
_compile = iso_svrl_for_xslt1
|
241 |
+
|
242 |
+
# etree.xpath object that determines input document validity when applied to
|
243 |
+
# the svrl result report; must return a list of result elements (empty if
|
244 |
+
# valid)
|
245 |
+
_validation_errors = ASSERTS_ONLY
|
246 |
+
|
247 |
+
def __init__(self, etree=None, file=None, include=True, expand=True,
|
248 |
+
include_params={}, expand_params={}, compile_params={},
|
249 |
+
store_schematron=False, store_xslt=False, store_report=False,
|
250 |
+
phase=None, error_finder=ASSERTS_ONLY,
|
251 |
+
validate_schema=schematron_schema_valid_supported):
|
252 |
+
super().__init__()
|
253 |
+
|
254 |
+
self._store_report = store_report
|
255 |
+
self._schematron = None
|
256 |
+
self._validator_xslt = None
|
257 |
+
self._validation_report = None
|
258 |
+
if error_finder is not self.ASSERTS_ONLY:
|
259 |
+
self._validation_errors = error_finder
|
260 |
+
|
261 |
+
# parse schema document, may be a schematron schema or an XML Schema or
|
262 |
+
# a RelaxNG schema with embedded schematron rules
|
263 |
+
root = None
|
264 |
+
try:
|
265 |
+
if etree is not None:
|
266 |
+
if _etree.iselement(etree):
|
267 |
+
root = etree
|
268 |
+
else:
|
269 |
+
root = etree.getroot()
|
270 |
+
elif file is not None:
|
271 |
+
root = _etree.parse(file).getroot()
|
272 |
+
except Exception:
|
273 |
+
raise _etree.SchematronParseError(
|
274 |
+
"No tree or file given: %s" % sys.exc_info()[1])
|
275 |
+
if root is None:
|
276 |
+
raise ValueError("Empty tree")
|
277 |
+
if root.tag == _schematron_root:
|
278 |
+
schematron = root
|
279 |
+
else:
|
280 |
+
schematron = self._extract(root)
|
281 |
+
if schematron is None:
|
282 |
+
raise _etree.SchematronParseError(
|
283 |
+
"Document is not a schematron schema or schematron-extractable")
|
284 |
+
# perform the iso-schematron skeleton implementation steps to get a
|
285 |
+
# validating xslt
|
286 |
+
if include:
|
287 |
+
schematron = self._include(schematron, **include_params)
|
288 |
+
if expand:
|
289 |
+
schematron = self._expand(schematron, **expand_params)
|
290 |
+
if validate_schema and not schematron_schema_valid(schematron):
|
291 |
+
raise _etree.SchematronParseError(
|
292 |
+
"invalid schematron schema: %s" %
|
293 |
+
schematron_schema_valid.error_log)
|
294 |
+
if store_schematron:
|
295 |
+
self._schematron = schematron
|
296 |
+
# add new compile keyword args here if exposing them
|
297 |
+
compile_kwargs = {'phase': phase}
|
298 |
+
compile_params = _stylesheet_param_dict(compile_params, compile_kwargs)
|
299 |
+
validator_xslt = self._compile(schematron, **compile_params)
|
300 |
+
if store_xslt:
|
301 |
+
self._validator_xslt = validator_xslt
|
302 |
+
self._validator = _etree.XSLT(validator_xslt)
|
303 |
+
|
304 |
+
def __call__(self, etree):
|
305 |
+
"""Validate doc using Schematron.
|
306 |
+
|
307 |
+
Returns true if document is valid, false if not.
|
308 |
+
"""
|
309 |
+
self._clear_error_log()
|
310 |
+
result = self._validator(etree)
|
311 |
+
if self._store_report:
|
312 |
+
self._validation_report = result
|
313 |
+
errors = self._validation_errors(result)
|
314 |
+
if errors:
|
315 |
+
if _etree.iselement(etree):
|
316 |
+
fname = etree.getroottree().docinfo.URL or '<file>'
|
317 |
+
else:
|
318 |
+
fname = etree.docinfo.URL or '<file>'
|
319 |
+
for error in errors:
|
320 |
+
# Does svrl report the line number, anywhere? Don't think so.
|
321 |
+
self._append_log_message(
|
322 |
+
domain=self._domain, type=self._error_type,
|
323 |
+
level=self._level, line=0,
|
324 |
+
message=_etree.tostring(error, encoding='unicode'),
|
325 |
+
filename=fname)
|
326 |
+
return False
|
327 |
+
return True
|
328 |
+
|
329 |
+
@property
|
330 |
+
def schematron(self):
|
331 |
+
"""ISO-schematron schema document (None if object has been initialized
|
332 |
+
with store_schematron=False).
|
333 |
+
"""
|
334 |
+
return self._schematron
|
335 |
+
|
336 |
+
@property
|
337 |
+
def validator_xslt(self):
|
338 |
+
"""ISO-schematron skeleton implementation XSLT validator document (None
|
339 |
+
if object has been initialized with store_xslt=False).
|
340 |
+
"""
|
341 |
+
return self._validator_xslt
|
342 |
+
|
343 |
+
@property
|
344 |
+
def validation_report(self):
|
345 |
+
"""ISO-schematron validation result report (None if result-storing has
|
346 |
+
been turned off).
|
347 |
+
"""
|
348 |
+
return self._validation_report
|
llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (10.4 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/rng/iso-schematron.rng
ADDED
@@ -0,0 +1,709 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
2 |
+
<!-- Copyright © ISO/IEC 2015 -->
|
3 |
+
<!--
|
4 |
+
The following permission notice and disclaimer shall be included in all
|
5 |
+
copies of this XML schema ("the Schema"), and derivations of the Schema:
|
6 |
+
|
7 |
+
Permission is hereby granted, free of charge in perpetuity, to any
|
8 |
+
person obtaining a copy of the Schema, to use, copy, modify, merge and
|
9 |
+
distribute free of charge, copies of the Schema for the purposes of
|
10 |
+
developing, implementing, installing and using software based on the
|
11 |
+
Schema, and to permit persons to whom the Schema is furnished to do so,
|
12 |
+
subject to the following conditions:
|
13 |
+
|
14 |
+
THE SCHEMA IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
15 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
16 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
17 |
+
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
18 |
+
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
19 |
+
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SCHEMA OR THE USE OR
|
20 |
+
OTHER DEALINGS IN THE SCHEMA.
|
21 |
+
|
22 |
+
In addition, any modified copy of the Schema shall include the following
|
23 |
+
notice:
|
24 |
+
|
25 |
+
"THIS SCHEMA HAS BEEN MODIFIED FROM THE SCHEMA DEFINED IN ISO/IEC 19757-3,
|
26 |
+
AND SHOULD NOT BE INTERPRETED AS COMPLYING WITH THAT STANDARD".
|
27 |
+
-->
|
28 |
+
<grammar ns="http://purl.oclc.org/dsdl/schematron" xmlns="http://relaxng.org/ns/structure/1.0" datatypeLibrary="http://www.w3.org/2001/XMLSchema-datatypes">
|
29 |
+
<start>
|
30 |
+
<ref name="schema"/>
|
31 |
+
</start>
|
32 |
+
<!-- Element declarations -->
|
33 |
+
<define name="schema">
|
34 |
+
<element name="schema">
|
35 |
+
<optional>
|
36 |
+
<attribute name="id">
|
37 |
+
<data type="ID"/>
|
38 |
+
</attribute>
|
39 |
+
</optional>
|
40 |
+
<ref name="rich"/>
|
41 |
+
<optional>
|
42 |
+
<attribute name="schemaVersion">
|
43 |
+
<ref name="non-empty-string"/>
|
44 |
+
</attribute>
|
45 |
+
</optional>
|
46 |
+
<optional>
|
47 |
+
<attribute name="defaultPhase">
|
48 |
+
<data type="IDREF"/>
|
49 |
+
</attribute>
|
50 |
+
</optional>
|
51 |
+
<optional>
|
52 |
+
<attribute name="queryBinding">
|
53 |
+
<ref name="non-empty-string"/>
|
54 |
+
</attribute>
|
55 |
+
</optional>
|
56 |
+
<interleave>
|
57 |
+
<ref name="foreign"/>
|
58 |
+
<zeroOrMore>
|
59 |
+
<ref name="inclusion"/>
|
60 |
+
</zeroOrMore>
|
61 |
+
<group>
|
62 |
+
<optional>
|
63 |
+
<ref name="title"/>
|
64 |
+
</optional>
|
65 |
+
<zeroOrMore>
|
66 |
+
<ref name="ns"/>
|
67 |
+
</zeroOrMore>
|
68 |
+
<zeroOrMore>
|
69 |
+
<ref name="p"/>
|
70 |
+
</zeroOrMore>
|
71 |
+
<zeroOrMore>
|
72 |
+
<ref name="let"/>
|
73 |
+
</zeroOrMore>
|
74 |
+
<zeroOrMore>
|
75 |
+
<ref name="phase"/>
|
76 |
+
</zeroOrMore>
|
77 |
+
<oneOrMore>
|
78 |
+
<ref name="pattern"/>
|
79 |
+
</oneOrMore>
|
80 |
+
<zeroOrMore>
|
81 |
+
<ref name="p"/>
|
82 |
+
</zeroOrMore>
|
83 |
+
<optional>
|
84 |
+
<ref name="diagnostics"/>
|
85 |
+
</optional>
|
86 |
+
<optional>
|
87 |
+
<!-- edited (lxml): required in standard, optional here (since it can be empty anyway) -->
|
88 |
+
<ref name="properties"/>
|
89 |
+
</optional>
|
90 |
+
</group>
|
91 |
+
</interleave>
|
92 |
+
</element>
|
93 |
+
</define>
|
94 |
+
<define name="active">
|
95 |
+
<element name="active">
|
96 |
+
<attribute name="pattern">
|
97 |
+
<data type="IDREF"/>
|
98 |
+
</attribute>
|
99 |
+
<interleave>
|
100 |
+
<ref name="foreign"/>
|
101 |
+
<zeroOrMore>
|
102 |
+
<choice>
|
103 |
+
<text/>
|
104 |
+
<ref name="dir"/>
|
105 |
+
<ref name="emph"/>
|
106 |
+
<ref name="span"/>
|
107 |
+
</choice>
|
108 |
+
</zeroOrMore>
|
109 |
+
</interleave>
|
110 |
+
</element>
|
111 |
+
</define>
|
112 |
+
<define name="assert">
|
113 |
+
<element name="assert">
|
114 |
+
<attribute name="test">
|
115 |
+
<ref name="exprValue"/>
|
116 |
+
</attribute>
|
117 |
+
<optional>
|
118 |
+
<attribute name="flag">
|
119 |
+
<ref name="flagValue"/>
|
120 |
+
</attribute>
|
121 |
+
</optional>
|
122 |
+
<optional>
|
123 |
+
<attribute name="id">
|
124 |
+
<data type="ID"/>
|
125 |
+
</attribute>
|
126 |
+
</optional>
|
127 |
+
<optional>
|
128 |
+
<attribute name="diagnostics">
|
129 |
+
<data type="IDREFS"/>
|
130 |
+
</attribute>
|
131 |
+
</optional>
|
132 |
+
<optional>
|
133 |
+
<attribute name="properties">
|
134 |
+
<data type="IDREFS"/>
|
135 |
+
</attribute>
|
136 |
+
</optional>
|
137 |
+
<ref name="rich"/>
|
138 |
+
<ref name="linkable"/>
|
139 |
+
<interleave>
|
140 |
+
<ref name="foreign"/>
|
141 |
+
<zeroOrMore>
|
142 |
+
<choice>
|
143 |
+
<text/>
|
144 |
+
<ref name="name"/>
|
145 |
+
<ref name="value-of"/>
|
146 |
+
<ref name="emph"/>
|
147 |
+
<ref name="dir"/>
|
148 |
+
<ref name="span"/>
|
149 |
+
</choice>
|
150 |
+
</zeroOrMore>
|
151 |
+
</interleave>
|
152 |
+
</element>
|
153 |
+
</define>
|
154 |
+
<define name="diagnostic">
|
155 |
+
<element name="diagnostic">
|
156 |
+
<attribute name="id">
|
157 |
+
<data type="ID"/>
|
158 |
+
</attribute>
|
159 |
+
<ref name="rich"/>
|
160 |
+
<interleave>
|
161 |
+
<ref name="foreign"/>
|
162 |
+
<zeroOrMore>
|
163 |
+
<choice>
|
164 |
+
<text/>
|
165 |
+
<ref name="value-of"/>
|
166 |
+
<ref name="emph"/>
|
167 |
+
<ref name="dir"/>
|
168 |
+
<ref name="span"/>
|
169 |
+
</choice>
|
170 |
+
</zeroOrMore>
|
171 |
+
</interleave>
|
172 |
+
</element>
|
173 |
+
</define>
|
174 |
+
<define name="diagnostics">
|
175 |
+
<element name="diagnostics">
|
176 |
+
<interleave>
|
177 |
+
<ref name="foreign"/>
|
178 |
+
<zeroOrMore>
|
179 |
+
<ref name="inclusion"/>
|
180 |
+
</zeroOrMore>
|
181 |
+
<zeroOrMore>
|
182 |
+
<ref name="diagnostic"/>
|
183 |
+
</zeroOrMore>
|
184 |
+
</interleave>
|
185 |
+
</element>
|
186 |
+
</define>
|
187 |
+
<define name="dir">
|
188 |
+
<element name="dir">
|
189 |
+
<optional>
|
190 |
+
<attribute name="value">
|
191 |
+
<choice>
|
192 |
+
<value>ltr</value>
|
193 |
+
<value>rtl</value>
|
194 |
+
</choice>
|
195 |
+
</attribute>
|
196 |
+
</optional>
|
197 |
+
<interleave>
|
198 |
+
<ref name="foreign"/>
|
199 |
+
<text/>
|
200 |
+
</interleave>
|
201 |
+
</element>
|
202 |
+
</define>
|
203 |
+
<define name="emph">
|
204 |
+
<element name="emph">
|
205 |
+
<text/>
|
206 |
+
</element>
|
207 |
+
</define>
|
208 |
+
<define name="extends">
|
209 |
+
<element name="extends">
|
210 |
+
<choice>
|
211 |
+
<attribute name="rule">
|
212 |
+
<data type="IDREF"/>
|
213 |
+
</attribute>
|
214 |
+
<attribute name="href">
|
215 |
+
<ref name="uriValue"/>
|
216 |
+
</attribute>
|
217 |
+
</choice>
|
218 |
+
<ref name="foreign-empty"/>
|
219 |
+
</element>
|
220 |
+
</define>
|
221 |
+
<define name="let">
|
222 |
+
<element name="let">
|
223 |
+
<attribute name="name">
|
224 |
+
<ref name="nameValue"/>
|
225 |
+
</attribute>
|
226 |
+
<choice>
|
227 |
+
<attribute name="value">
|
228 |
+
<data type="string" datatypeLibrary=""/>
|
229 |
+
</attribute>
|
230 |
+
<oneOrMore>
|
231 |
+
<ref name="foreign-element"/>
|
232 |
+
</oneOrMore>
|
233 |
+
</choice>
|
234 |
+
</element>
|
235 |
+
</define>
|
236 |
+
<define name="name">
|
237 |
+
<element name="name">
|
238 |
+
<optional>
|
239 |
+
<attribute name="path">
|
240 |
+
<ref name="pathValue"/>
|
241 |
+
</attribute>
|
242 |
+
</optional>
|
243 |
+
<ref name="foreign-empty"/>
|
244 |
+
</element>
|
245 |
+
</define>
|
246 |
+
<define name="ns">
|
247 |
+
<element name="ns">
|
248 |
+
<attribute name="uri">
|
249 |
+
<ref name="uriValue"/>
|
250 |
+
</attribute>
|
251 |
+
<attribute name="prefix">
|
252 |
+
<ref name="nameValue"/>
|
253 |
+
</attribute>
|
254 |
+
<ref name="foreign-empty"/>
|
255 |
+
</element>
|
256 |
+
</define>
|
257 |
+
<define name="p">
|
258 |
+
<element name="p">
|
259 |
+
<optional>
|
260 |
+
<attribute name="id">
|
261 |
+
<data type="ID"/>
|
262 |
+
</attribute>
|
263 |
+
</optional>
|
264 |
+
<optional>
|
265 |
+
<attribute name="class">
|
266 |
+
<ref name="classValue"/>
|
267 |
+
</attribute>
|
268 |
+
</optional>
|
269 |
+
<optional>
|
270 |
+
<attribute name="icon">
|
271 |
+
<ref name="uriValue"/>
|
272 |
+
</attribute>
|
273 |
+
</optional>
|
274 |
+
<interleave>
|
275 |
+
<ref name="foreign"/>
|
276 |
+
<zeroOrMore>
|
277 |
+
<choice>
|
278 |
+
<text/>
|
279 |
+
<ref name="dir"/>
|
280 |
+
<ref name="emph"/>
|
281 |
+
<ref name="span"/>
|
282 |
+
</choice>
|
283 |
+
</zeroOrMore>
|
284 |
+
</interleave>
|
285 |
+
</element>
|
286 |
+
</define>
|
287 |
+
<define name="param">
|
288 |
+
<element name="param">
|
289 |
+
<attribute name="name">
|
290 |
+
<ref name="nameValue"/>
|
291 |
+
</attribute>
|
292 |
+
<attribute name="value">
|
293 |
+
<ref name="non-empty-string"/>
|
294 |
+
</attribute>
|
295 |
+
</element>
|
296 |
+
</define>
|
297 |
+
<define name="pattern">
|
298 |
+
<element name="pattern">
|
299 |
+
<optional>
|
300 |
+
<attribute name="documents">
|
301 |
+
<ref name="pathValue"/>
|
302 |
+
</attribute>
|
303 |
+
</optional>
|
304 |
+
<ref name="rich"/>
|
305 |
+
<interleave>
|
306 |
+
<ref name="foreign"/>
|
307 |
+
<zeroOrMore>
|
308 |
+
<ref name="inclusion"/>
|
309 |
+
</zeroOrMore>
|
310 |
+
<choice>
|
311 |
+
<group>
|
312 |
+
<attribute name="abstract">
|
313 |
+
<value>true</value>
|
314 |
+
</attribute>
|
315 |
+
<attribute name="id">
|
316 |
+
<data type="ID"/>
|
317 |
+
</attribute>
|
318 |
+
<optional>
|
319 |
+
<ref name="title"/>
|
320 |
+
</optional>
|
321 |
+
<group>
|
322 |
+
<zeroOrMore>
|
323 |
+
<ref name="p"/>
|
324 |
+
</zeroOrMore>
|
325 |
+
<zeroOrMore>
|
326 |
+
<ref name="let"/>
|
327 |
+
</zeroOrMore>
|
328 |
+
<zeroOrMore>
|
329 |
+
<ref name="rule"/>
|
330 |
+
</zeroOrMore>
|
331 |
+
</group>
|
332 |
+
</group>
|
333 |
+
<group>
|
334 |
+
<optional>
|
335 |
+
<attribute name="abstract">
|
336 |
+
<value>false</value>
|
337 |
+
</attribute>
|
338 |
+
</optional>
|
339 |
+
<optional>
|
340 |
+
<attribute name="id">
|
341 |
+
<data type="ID"/>
|
342 |
+
</attribute>
|
343 |
+
</optional>
|
344 |
+
<optional>
|
345 |
+
<ref name="title"/>
|
346 |
+
</optional>
|
347 |
+
<group>
|
348 |
+
<zeroOrMore>
|
349 |
+
<ref name="p"/>
|
350 |
+
</zeroOrMore>
|
351 |
+
<zeroOrMore>
|
352 |
+
<ref name="let"/>
|
353 |
+
</zeroOrMore>
|
354 |
+
<zeroOrMore>
|
355 |
+
<ref name="rule"/>
|
356 |
+
</zeroOrMore>
|
357 |
+
</group>
|
358 |
+
</group>
|
359 |
+
<group>
|
360 |
+
<optional>
|
361 |
+
<attribute name="abstract">
|
362 |
+
<value>false</value>
|
363 |
+
</attribute>
|
364 |
+
</optional>
|
365 |
+
<attribute name="is-a">
|
366 |
+
<data type="IDREF"/>
|
367 |
+
</attribute>
|
368 |
+
<optional>
|
369 |
+
<attribute name="id">
|
370 |
+
<data type="ID"/>
|
371 |
+
</attribute>
|
372 |
+
</optional>
|
373 |
+
<optional>
|
374 |
+
<ref name="title"/>
|
375 |
+
</optional>
|
376 |
+
<group>
|
377 |
+
<zeroOrMore>
|
378 |
+
<ref name="p"/>
|
379 |
+
</zeroOrMore>
|
380 |
+
<zeroOrMore>
|
381 |
+
<ref name="param"/>
|
382 |
+
</zeroOrMore>
|
383 |
+
</group>
|
384 |
+
</group>
|
385 |
+
</choice>
|
386 |
+
</interleave>
|
387 |
+
</element>
|
388 |
+
</define>
|
389 |
+
<define name="phase">
|
390 |
+
<element name="phase">
|
391 |
+
<attribute name="id">
|
392 |
+
<data type="ID"/>
|
393 |
+
</attribute>
|
394 |
+
<ref name="rich"/>
|
395 |
+
<interleave>
|
396 |
+
<ref name="foreign"/>
|
397 |
+
<zeroOrMore>
|
398 |
+
<ref name="inclusion"/>
|
399 |
+
</zeroOrMore>
|
400 |
+
<group>
|
401 |
+
<zeroOrMore>
|
402 |
+
<ref name="p"/>
|
403 |
+
</zeroOrMore>
|
404 |
+
<zeroOrMore>
|
405 |
+
<ref name="let"/>
|
406 |
+
</zeroOrMore>
|
407 |
+
<zeroOrMore>
|
408 |
+
<ref name="active"/>
|
409 |
+
</zeroOrMore>
|
410 |
+
</group>
|
411 |
+
</interleave>
|
412 |
+
</element>
|
413 |
+
</define>
|
414 |
+
<define name="properties">
|
415 |
+
<element name="properties">
|
416 |
+
<zeroOrMore>
|
417 |
+
<ref name="property"/>
|
418 |
+
</zeroOrMore>
|
419 |
+
</element>
|
420 |
+
</define>
|
421 |
+
<define name="property">
|
422 |
+
<element name="property">
|
423 |
+
<attribute name="id">
|
424 |
+
<data type="ID"/>
|
425 |
+
</attribute>
|
426 |
+
<optional>
|
427 |
+
<attribute name="role">
|
428 |
+
<ref name="roleValue"/>
|
429 |
+
</attribute>
|
430 |
+
</optional>
|
431 |
+
<optional>
|
432 |
+
<attribute name="scheme"/>
|
433 |
+
</optional>
|
434 |
+
<interleave>
|
435 |
+
<ref name="foreign"/>
|
436 |
+
<zeroOrMore>
|
437 |
+
<choice>
|
438 |
+
<text/>
|
439 |
+
<ref name="name"/>
|
440 |
+
<ref name="value-of"/>
|
441 |
+
<ref name="emph"/>
|
442 |
+
<ref name="dir"/>
|
443 |
+
<ref name="span"/>
|
444 |
+
</choice>
|
445 |
+
</zeroOrMore>
|
446 |
+
</interleave>
|
447 |
+
</element>
|
448 |
+
</define>
|
449 |
+
<define name="report">
|
450 |
+
<element name="report">
|
451 |
+
<attribute name="test">
|
452 |
+
<ref name="exprValue"/>
|
453 |
+
</attribute>
|
454 |
+
<optional>
|
455 |
+
<attribute name="flag">
|
456 |
+
<ref name="flagValue"/>
|
457 |
+
</attribute>
|
458 |
+
</optional>
|
459 |
+
<optional>
|
460 |
+
<attribute name="id">
|
461 |
+
<data type="ID"/>
|
462 |
+
</attribute>
|
463 |
+
</optional>
|
464 |
+
<optional>
|
465 |
+
<attribute name="diagnostics">
|
466 |
+
<data type="IDREFS"/>
|
467 |
+
</attribute>
|
468 |
+
</optional>
|
469 |
+
<optional>
|
470 |
+
<attribute name="properties">
|
471 |
+
<data type="IDREFS"/>
|
472 |
+
</attribute>
|
473 |
+
</optional>
|
474 |
+
<ref name="rich"/>
|
475 |
+
<ref name="linkable"/>
|
476 |
+
<interleave>
|
477 |
+
<ref name="foreign"/>
|
478 |
+
<zeroOrMore>
|
479 |
+
<choice>
|
480 |
+
<text/>
|
481 |
+
<ref name="name"/>
|
482 |
+
<ref name="value-of"/>
|
483 |
+
<ref name="emph"/>
|
484 |
+
<ref name="dir"/>
|
485 |
+
<ref name="span"/>
|
486 |
+
</choice>
|
487 |
+
</zeroOrMore>
|
488 |
+
</interleave>
|
489 |
+
</element>
|
490 |
+
</define>
|
491 |
+
<define name="rule">
|
492 |
+
<element name="rule">
|
493 |
+
<optional>
|
494 |
+
<attribute name="flag">
|
495 |
+
<ref name="flagValue"/>
|
496 |
+
</attribute>
|
497 |
+
</optional>
|
498 |
+
<ref name="rich"/>
|
499 |
+
<ref name="linkable"/>
|
500 |
+
<interleave>
|
501 |
+
<ref name="foreign"/>
|
502 |
+
<zeroOrMore>
|
503 |
+
<ref name="inclusion"/>
|
504 |
+
</zeroOrMore>
|
505 |
+
<choice>
|
506 |
+
<group>
|
507 |
+
<attribute name="abstract">
|
508 |
+
<value>true</value>
|
509 |
+
</attribute>
|
510 |
+
<attribute name="id">
|
511 |
+
<data type="ID"/>
|
512 |
+
</attribute>
|
513 |
+
<zeroOrMore>
|
514 |
+
<ref name="let"/>
|
515 |
+
</zeroOrMore>
|
516 |
+
<oneOrMore>
|
517 |
+
<choice>
|
518 |
+
<ref name="assert"/>
|
519 |
+
<ref name="report"/>
|
520 |
+
<ref name="extends"/>
|
521 |
+
<ref name="p"/>
|
522 |
+
</choice>
|
523 |
+
</oneOrMore>
|
524 |
+
</group>
|
525 |
+
<group>
|
526 |
+
<attribute name="context">
|
527 |
+
<ref name="pathValue"/>
|
528 |
+
</attribute>
|
529 |
+
<optional>
|
530 |
+
<attribute name="id">
|
531 |
+
<data type="ID"/>
|
532 |
+
</attribute>
|
533 |
+
</optional>
|
534 |
+
<optional>
|
535 |
+
<attribute name="abstract">
|
536 |
+
<value>false</value>
|
537 |
+
</attribute>
|
538 |
+
</optional>
|
539 |
+
<zeroOrMore>
|
540 |
+
<ref name="let"/>
|
541 |
+
</zeroOrMore>
|
542 |
+
<oneOrMore>
|
543 |
+
<choice>
|
544 |
+
<ref name="assert"/>
|
545 |
+
<ref name="report"/>
|
546 |
+
<ref name="extends"/>
|
547 |
+
<ref name="p"/>
|
548 |
+
</choice>
|
549 |
+
</oneOrMore>
|
550 |
+
</group>
|
551 |
+
</choice>
|
552 |
+
</interleave>
|
553 |
+
</element>
|
554 |
+
</define>
|
555 |
+
<define name="span">
|
556 |
+
<element name="span">
|
557 |
+
<attribute name="class">
|
558 |
+
<ref name="classValue"/>
|
559 |
+
</attribute>
|
560 |
+
<interleave>
|
561 |
+
<ref name="foreign"/>
|
562 |
+
<text/>
|
563 |
+
</interleave>
|
564 |
+
</element>
|
565 |
+
</define>
|
566 |
+
<define name="title">
|
567 |
+
<element name="title">
|
568 |
+
<zeroOrMore>
|
569 |
+
<choice>
|
570 |
+
<text/>
|
571 |
+
<ref name="dir"/>
|
572 |
+
</choice>
|
573 |
+
</zeroOrMore>
|
574 |
+
</element>
|
575 |
+
</define>
|
576 |
+
<define name="value-of">
|
577 |
+
<element name="value-of">
|
578 |
+
<attribute name="select">
|
579 |
+
<ref name="pathValue"/>
|
580 |
+
</attribute>
|
581 |
+
<ref name="foreign-empty"/>
|
582 |
+
</element>
|
583 |
+
</define>
|
584 |
+
<!-- common declarations -->
|
585 |
+
<define name="inclusion">
|
586 |
+
<element name="include">
|
587 |
+
<attribute name="href">
|
588 |
+
<ref name="uriValue"/>
|
589 |
+
</attribute>
|
590 |
+
<ref name="foreign-empty"/>
|
591 |
+
</element>
|
592 |
+
</define>
|
593 |
+
<define name="rich">
|
594 |
+
<optional>
|
595 |
+
<attribute name="icon">
|
596 |
+
<ref name="uriValue"/>
|
597 |
+
</attribute>
|
598 |
+
</optional>
|
599 |
+
<optional>
|
600 |
+
<attribute name="see">
|
601 |
+
<ref name="uriValue"/>
|
602 |
+
</attribute>
|
603 |
+
</optional>
|
604 |
+
<optional>
|
605 |
+
<attribute name="fpi">
|
606 |
+
<ref name="fpiValue"/>
|
607 |
+
</attribute>
|
608 |
+
</optional>
|
609 |
+
<optional>
|
610 |
+
<attribute name="xml:lang">
|
611 |
+
<ref name="langValue"/>
|
612 |
+
</attribute>
|
613 |
+
</optional>
|
614 |
+
<optional>
|
615 |
+
<attribute name="xml:space">
|
616 |
+
<choice>
|
617 |
+
<value>preserve</value>
|
618 |
+
<value>default</value>
|
619 |
+
</choice>
|
620 |
+
</attribute>
|
621 |
+
</optional>
|
622 |
+
</define>
|
623 |
+
<define name="linkable">
|
624 |
+
<optional>
|
625 |
+
<attribute name="role">
|
626 |
+
<ref name="roleValue"/>
|
627 |
+
</attribute>
|
628 |
+
</optional>
|
629 |
+
<optional>
|
630 |
+
<attribute name="subject">
|
631 |
+
<ref name="pathValue"/>
|
632 |
+
</attribute>
|
633 |
+
</optional>
|
634 |
+
</define>
|
635 |
+
<define name="foreign">
|
636 |
+
<ref name="foreign-attributes"/>
|
637 |
+
<zeroOrMore>
|
638 |
+
<ref name="foreign-element"/>
|
639 |
+
</zeroOrMore>
|
640 |
+
</define>
|
641 |
+
<define name="foreign-empty">
|
642 |
+
<ref name="foreign-attributes"/>
|
643 |
+
</define>
|
644 |
+
<define name="foreign-attributes">
|
645 |
+
<zeroOrMore>
|
646 |
+
<attribute>
|
647 |
+
<anyName>
|
648 |
+
<except>
|
649 |
+
<nsName ns=""/>
|
650 |
+
<nsName ns="http://www.w3.org/XML/1998/namespace"/>
|
651 |
+
</except>
|
652 |
+
</anyName>
|
653 |
+
</attribute>
|
654 |
+
</zeroOrMore>
|
655 |
+
</define>
|
656 |
+
<define name="foreign-element">
|
657 |
+
<element>
|
658 |
+
<anyName>
|
659 |
+
<except>
|
660 |
+
<nsName/>
|
661 |
+
</except>
|
662 |
+
</anyName>
|
663 |
+
<zeroOrMore>
|
664 |
+
<choice>
|
665 |
+
<attribute>
|
666 |
+
<anyName/>
|
667 |
+
</attribute>
|
668 |
+
<ref name="foreign-element"/>
|
669 |
+
<ref name="schema"/>
|
670 |
+
<text/>
|
671 |
+
</choice>
|
672 |
+
</zeroOrMore>
|
673 |
+
</element>
|
674 |
+
</define>
|
675 |
+
<!-- Data types -->
|
676 |
+
<define name="uriValue">
|
677 |
+
<data type="anyURI"/>
|
678 |
+
</define>
|
679 |
+
<define name="pathValue">
|
680 |
+
<data type="string" datatypeLibrary=""/>
|
681 |
+
</define>
|
682 |
+
<define name="exprValue">
|
683 |
+
<data type="string" datatypeLibrary=""/>
|
684 |
+
</define>
|
685 |
+
<define name="fpiValue">
|
686 |
+
<data type="string" datatypeLibrary=""/>
|
687 |
+
</define>
|
688 |
+
<define name="langValue">
|
689 |
+
<data type="language"/>
|
690 |
+
</define>
|
691 |
+
<define name="roleValue">
|
692 |
+
<data type="string" datatypeLibrary=""/>
|
693 |
+
</define>
|
694 |
+
<define name="flagValue">
|
695 |
+
<data type="string" datatypeLibrary=""/>
|
696 |
+
</define>
|
697 |
+
<define name="nameValue">
|
698 |
+
<data type="string" datatypeLibrary=""/>
|
699 |
+
</define>
|
700 |
+
<!-- In the default query language binding, xsd:NCNAME -->
|
701 |
+
<define name="classValue">
|
702 |
+
<data type="string" datatypeLibrary=""/>
|
703 |
+
</define>
|
704 |
+
<define name="non-empty-string">
|
705 |
+
<data type="token">
|
706 |
+
<param name="minLength">1</param>
|
707 |
+
</data>
|
708 |
+
</define>
|
709 |
+
</grammar>
|
llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/RNG2Schtrn.xsl
ADDED
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
2 |
+
<!--
|
3 |
+
Stylesheet for extracting Schematron information from a RELAX-NG schema.
|
4 |
+
Based on the stylesheet for extracting Schematron information from W3C XML Schema.
|
5 |
+
Created by Eddie Robertsson 2002/06/01
|
6 |
+
2009/12/10 hj: changed Schematron namespace to ISO URI (Holger Joukl)
|
7 |
+
-->
|
8 |
+
<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
|
9 |
+
xmlns:sch="http://purl.oclc.org/dsdl/schematron" xmlns:rng="http://relaxng.org/ns/structure/1.0">
|
10 |
+
<!-- Set the output to be XML with an XML declaration and use indentation -->
|
11 |
+
<xsl:output method="xml" omit-xml-declaration="no" indent="yes" standalone="yes"/>
|
12 |
+
<!-- -->
|
13 |
+
<!-- match schema and call recursive template to extract included schemas -->
|
14 |
+
<!-- -->
|
15 |
+
<xsl:template match="/rng:grammar | /rng:element">
|
16 |
+
<!-- call the schema definition template ... -->
|
17 |
+
<xsl:call-template name="gatherSchema">
|
18 |
+
<!-- ... with current node as the $schemas parameter ... -->
|
19 |
+
<xsl:with-param name="schemas" select="."/>
|
20 |
+
<!-- ... and any includes in the $include parameter -->
|
21 |
+
<xsl:with-param name="includes" select="document(/rng:grammar/rng:include/@href
|
22 |
+
| //rng:externalRef/@href)"/>
|
23 |
+
</xsl:call-template>
|
24 |
+
</xsl:template>
|
25 |
+
<!-- -->
|
26 |
+
<!-- gather all included schemas into a single parameter variable -->
|
27 |
+
<!-- -->
|
28 |
+
<xsl:template name="gatherSchema">
|
29 |
+
<xsl:param name="schemas"/>
|
30 |
+
<xsl:param name="includes"/>
|
31 |
+
<xsl:choose>
|
32 |
+
<xsl:when test="count($schemas) < count($schemas | $includes)">
|
33 |
+
<!-- when $includes includes something new, recurse ... -->
|
34 |
+
<xsl:call-template name="gatherSchema">
|
35 |
+
<!-- ... with current $includes added to the $schemas parameter ... -->
|
36 |
+
<xsl:with-param name="schemas" select="$schemas | $includes"/>
|
37 |
+
<!-- ... and any *new* includes in the $include parameter -->
|
38 |
+
<xsl:with-param name="includes" select="document($includes/rng:grammar/rng:include/@href
|
39 |
+
| $includes//rng:externalRef/@href)"/>
|
40 |
+
</xsl:call-template>
|
41 |
+
</xsl:when>
|
42 |
+
<xsl:otherwise>
|
43 |
+
<!-- we have the complete set of included schemas, so now let's output the embedded schematron -->
|
44 |
+
<xsl:call-template name="output">
|
45 |
+
<xsl:with-param name="schemas" select="$schemas"/>
|
46 |
+
</xsl:call-template>
|
47 |
+
</xsl:otherwise>
|
48 |
+
</xsl:choose>
|
49 |
+
</xsl:template>
|
50 |
+
<!-- -->
|
51 |
+
<!-- output the schematron information -->
|
52 |
+
<!-- -->
|
53 |
+
<xsl:template name="output">
|
54 |
+
<xsl:param name="schemas"/>
|
55 |
+
<!-- -->
|
56 |
+
<sch:schema>
|
57 |
+
<!-- get header-type elements - eg title and especially ns -->
|
58 |
+
<!-- title (just one) -->
|
59 |
+
<xsl:copy-of select="$schemas//sch:title[1]"/>
|
60 |
+
<!-- get remaining schematron schema children -->
|
61 |
+
<!-- get non-blank namespace elements, dropping duplicates -->
|
62 |
+
<xsl:for-each select="$schemas//sch:ns">
|
63 |
+
<xsl:if test="generate-id(.) = generate-id($schemas//sch:ns[@prefix = current()/@prefix][1])">
|
64 |
+
<xsl:copy-of select="."/>
|
65 |
+
</xsl:if>
|
66 |
+
</xsl:for-each>
|
67 |
+
<xsl:copy-of select="$schemas//sch:phase"/>
|
68 |
+
<xsl:copy-of select="$schemas//sch:pattern"/>
|
69 |
+
<sch:diagnostics>
|
70 |
+
<xsl:copy-of select="$schemas//sch:diagnostics/*"/>
|
71 |
+
</sch:diagnostics>
|
72 |
+
</sch:schema>
|
73 |
+
</xsl:template>
|
74 |
+
<!-- -->
|
75 |
+
</xsl:transform>
|
llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/XSD2Schtrn.xsl
ADDED
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
2 |
+
<!--
|
3 |
+
based on an original transform by Eddie Robertsson
|
4 |
+
2001/04/21 fn: added support for included schemas
|
5 |
+
2001/06/27 er: changed XMl Schema prefix from xsd: to xs: and changed to the Rec namespace
|
6 |
+
2009/12/10 hj: changed Schematron namespace to ISO URI (Holger Joukl)
|
7 |
+
-->
|
8 |
+
<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
|
9 |
+
xmlns:sch="http://purl.oclc.org/dsdl/schematron" xmlns:xs="http://www.w3.org/2001/XMLSchema">
|
10 |
+
<!-- Set the output to be XML with an XML declaration and use indentation -->
|
11 |
+
<xsl:output method="xml" omit-xml-declaration="no" indent="yes" standalone="yes"/>
|
12 |
+
<!-- -->
|
13 |
+
<!-- match schema and call recursive template to extract included schemas -->
|
14 |
+
<!-- -->
|
15 |
+
<xsl:template match="xs:schema">
|
16 |
+
<!-- call the schema definition template ... -->
|
17 |
+
<xsl:call-template name="gatherSchema">
|
18 |
+
<!-- ... with current current root as the $schemas parameter ... -->
|
19 |
+
<xsl:with-param name="schemas" select="/"/>
|
20 |
+
<!-- ... and any includes in the $include parameter -->
|
21 |
+
<xsl:with-param name="includes"
|
22 |
+
select="document(/xs:schema/xs:*[self::xs:include or self::xs:import or self::xs:redefine]/@schemaLocation)"/>
|
23 |
+
</xsl:call-template>
|
24 |
+
</xsl:template>
|
25 |
+
<!-- -->
|
26 |
+
<!-- gather all included schemas into a single parameter variable -->
|
27 |
+
<!-- -->
|
28 |
+
<xsl:template name="gatherSchema">
|
29 |
+
<xsl:param name="schemas"/>
|
30 |
+
<xsl:param name="includes"/>
|
31 |
+
<xsl:choose>
|
32 |
+
<xsl:when test="count($schemas) < count($schemas | $includes)">
|
33 |
+
<!-- when $includes includes something new, recurse ... -->
|
34 |
+
<xsl:call-template name="gatherSchema">
|
35 |
+
<!-- ... with current $includes added to the $schemas parameter ... -->
|
36 |
+
<xsl:with-param name="schemas" select="$schemas | $includes"/>
|
37 |
+
<!-- ... and any *new* includes in the $include parameter -->
|
38 |
+
<xsl:with-param name="includes"
|
39 |
+
select="document($includes/xs:schema/xs:*[self::xs:include or self::xs:import or self::xs:redefine]/@schemaLocation)"/>
|
40 |
+
</xsl:call-template>
|
41 |
+
</xsl:when>
|
42 |
+
<xsl:otherwise>
|
43 |
+
<!-- we have the complete set of included schemas,
|
44 |
+
so now let's output the embedded schematron -->
|
45 |
+
<xsl:call-template name="output">
|
46 |
+
<xsl:with-param name="schemas" select="$schemas"/>
|
47 |
+
</xsl:call-template>
|
48 |
+
</xsl:otherwise>
|
49 |
+
</xsl:choose>
|
50 |
+
</xsl:template>
|
51 |
+
<!-- -->
|
52 |
+
<!-- output the schematron information -->
|
53 |
+
<!-- -->
|
54 |
+
<xsl:template name="output">
|
55 |
+
<xsl:param name="schemas"/>
|
56 |
+
<!-- -->
|
57 |
+
<sch:schema>
|
58 |
+
<!-- get header-type elements - eg title and especially ns -->
|
59 |
+
<!-- title (just one) -->
|
60 |
+
<xsl:copy-of select="$schemas//xs:appinfo/sch:title[1]"/>
|
61 |
+
<!-- get remaining schematron schema children -->
|
62 |
+
<!-- get non-blank namespace elements, dropping duplicates -->
|
63 |
+
<xsl:for-each select="$schemas//xs:appinfo/sch:ns">
|
64 |
+
<xsl:if test="generate-id(.) =
|
65 |
+
generate-id($schemas//xs:appinfo/sch:ns[@prefix = current()/@prefix][1])">
|
66 |
+
<xsl:copy-of select="."/>
|
67 |
+
</xsl:if>
|
68 |
+
</xsl:for-each>
|
69 |
+
<xsl:copy-of select="$schemas//xs:appinfo/sch:phase"/>
|
70 |
+
<xsl:copy-of select="$schemas//xs:appinfo/sch:pattern"/>
|
71 |
+
<sch:diagnostics>
|
72 |
+
<xsl:copy-of select="$schemas//xs:appinfo/sch:diagnostics/*"/>
|
73 |
+
</sch:diagnostics>
|
74 |
+
</sch:schema>
|
75 |
+
</xsl:template>
|
76 |
+
<!-- -->
|
77 |
+
</xsl:transform>
|
llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_abstract_expand.xsl
ADDED
@@ -0,0 +1,313 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<?xml version="1.0" encoding="UTF-8"?><?xar XSLT?>
|
2 |
+
|
3 |
+
<!--
|
4 |
+
OVERVIEW - iso_abstract_expand.xsl
|
5 |
+
|
6 |
+
This is a preprocessor for ISO Schematron, which implements abstract patterns.
|
7 |
+
It also
|
8 |
+
* extracts a particular schema using an ID, where there are multiple
|
9 |
+
schemas, such as when they are embedded in the same NVDL script
|
10 |
+
* allows parameter substitution inside @context, @test, @select, @path
|
11 |
+
* experimentally, allows parameter recognition and substitution inside
|
12 |
+
text (NOTE: to be removed, for compataibility with other implementations,
|
13 |
+
please do not use this)
|
14 |
+
|
15 |
+
This should be used after iso-dsdl-include.xsl and before the skeleton or
|
16 |
+
meta-stylesheet (e.g. iso-svrl.xsl) . It only requires XSLT 1.
|
17 |
+
|
18 |
+
Each kind of inclusion can be turned off (or on) on the command line.
|
19 |
+
|
20 |
+
-->
|
21 |
+
|
22 |
+
<!--
|
23 |
+
Open Source Initiative OSI - The MIT License:Licensing
|
24 |
+
[OSI Approved License]
|
25 |
+
|
26 |
+
This source code was previously available under the zlib/libpng license.
|
27 |
+
Attribution is polite.
|
28 |
+
|
29 |
+
The MIT License
|
30 |
+
|
31 |
+
Copyright (c) 2004-2010 Rick Jellife and Academia Sinica Computing Centre, Taiwan
|
32 |
+
|
33 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
34 |
+
of this software and associated documentation files (the "Software"), to deal
|
35 |
+
in the Software without restriction, including without limitation the rights
|
36 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
37 |
+
copies of the Software, and to permit persons to whom the Software is
|
38 |
+
furnished to do so, subject to the following conditions:
|
39 |
+
|
40 |
+
The above copyright notice and this permission notice shall be included in
|
41 |
+
all copies or substantial portions of the Software.
|
42 |
+
|
43 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
44 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
45 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
46 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
47 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
48 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
49 |
+
THE SOFTWARE.
|
50 |
+
-->
|
51 |
+
|
52 |
+
<!--
|
53 |
+
VERSION INFORMATION
|
54 |
+
2013-09-19 RJ
|
55 |
+
* Allow macro expansion in @path attributes, eg. for sch:name/@path
|
56 |
+
|
57 |
+
2010-07-10 RJ
|
58 |
+
* Move to MIT license
|
59 |
+
|
60 |
+
2008-09-18 RJ
|
61 |
+
* move out param test from iso:schema template to work with XSLT 1. (Noah Fontes)
|
62 |
+
|
63 |
+
2008-07-29 RJ
|
64 |
+
* Create. Pull out as distinct XSL in its own namespace from old iso_pre_pro.xsl
|
65 |
+
* Put everything in private namespace
|
66 |
+
* Rewrite replace_substring named template so that copyright is clear
|
67 |
+
|
68 |
+
2008-07-24 RJ
|
69 |
+
* correct abstract patterns so for correct names: param/@name and
|
70 |
+
param/@value
|
71 |
+
|
72 |
+
2007-01-12 RJ
|
73 |
+
* Use ISO namespace
|
74 |
+
* Use pattern/@id not pattern/@name
|
75 |
+
* Add Oliver Becker's suggests from old Schematron-love-in list for <copy>
|
76 |
+
* Add XT -ism?
|
77 |
+
2003 RJ
|
78 |
+
* Original written for old namespace
|
79 |
+
* http://www.topologi.com/resources/iso-pre-pro.xsl
|
80 |
+
-->
|
81 |
+
<xslt:stylesheet version="1.0" xmlns:xslt="http://www.w3.org/1999/XSL/Transform"
|
82 |
+
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
|
83 |
+
xmlns:iso="http://purl.oclc.org/dsdl/schematron"
|
84 |
+
xmlns:nvdl="http://purl.oclc.org/dsdl/nvdl"
|
85 |
+
|
86 |
+
xmlns:iae="http://www.schematron.com/namespace/iae"
|
87 |
+
|
88 |
+
>
|
89 |
+
|
90 |
+
<xslt:param name="schema-id"></xslt:param>
|
91 |
+
|
92 |
+
|
93 |
+
<!-- Driver for the mode -->
|
94 |
+
<xsl:template match="/">
|
95 |
+
<xsl:apply-templates select="." mode="iae:go" />
|
96 |
+
</xsl:template>
|
97 |
+
|
98 |
+
|
99 |
+
<!-- ================================================================================== -->
|
100 |
+
<!-- Normal processing rules -->
|
101 |
+
<!-- ================================================================================== -->
|
102 |
+
<!-- Output only the selected schema -->
|
103 |
+
<xslt:template match="iso:schema" >
|
104 |
+
<xsl:if test="string-length($schema-id) =0 or @id= $schema-id ">
|
105 |
+
<xslt:copy>
|
106 |
+
<xslt:copy-of select="@*" />
|
107 |
+
<xslt:apply-templates mode="iae:go" />
|
108 |
+
</xslt:copy>
|
109 |
+
</xsl:if>
|
110 |
+
</xslt:template>
|
111 |
+
|
112 |
+
|
113 |
+
<!-- Strip out any foreign elements above the Schematron schema .
|
114 |
+
-->
|
115 |
+
<xslt:template match="*[not(ancestor-or-self::iso:*)]" mode="iae:go" >
|
116 |
+
<xslt:apply-templates mode="iae:go" />
|
117 |
+
</xslt:template>
|
118 |
+
|
119 |
+
|
120 |
+
<!-- ================================================================================== -->
|
121 |
+
<!-- Handle Schematron abstract pattern preprocessing -->
|
122 |
+
<!-- abstract-to-real calls
|
123 |
+
do-pattern calls
|
124 |
+
macro-expand calls
|
125 |
+
multi-macro-expand
|
126 |
+
replace-substring -->
|
127 |
+
<!-- ================================================================================== -->
|
128 |
+
|
129 |
+
<!--
|
130 |
+
Abstract patterns allow you to say, for example
|
131 |
+
|
132 |
+
<pattern name="htmlTable" is-a="table">
|
133 |
+
<param name="row" value="html:tr"/>
|
134 |
+
<param name="cell" value="html:td" />
|
135 |
+
<param name="table" value="html:table" />
|
136 |
+
</pattern>
|
137 |
+
|
138 |
+
For a good introduction, see Uche Ogbujii's article for IBM DeveloperWorks
|
139 |
+
"Discover the flexibility of Schematron abstract patterns"
|
140 |
+
http://www-128.ibm.com/developerworks/xml/library/x-stron.html
|
141 |
+
However, note that ISO Schematron uses @name and @value attributes on
|
142 |
+
the iso:param element, and @id not @name on the pattern element.
|
143 |
+
|
144 |
+
-->
|
145 |
+
|
146 |
+
<!-- Suppress declarations of abstract patterns -->
|
147 |
+
<xslt:template match="iso:pattern[@abstract='true']" mode="iae:go" >
|
148 |
+
<xslt:comment>Suppressed abstract pattern <xslt:value-of select="@id"/> was here</xslt:comment>
|
149 |
+
</xslt:template>
|
150 |
+
|
151 |
+
|
152 |
+
<!-- Suppress uses of abstract patterns -->
|
153 |
+
<xslt:template match="iso:pattern[@is-a]" mode="iae:go" >
|
154 |
+
|
155 |
+
<xslt:comment>Start pattern based on abstract <xslt:value-of select="@is-a"/></xslt:comment>
|
156 |
+
|
157 |
+
<xslt:call-template name="iae:abstract-to-real" >
|
158 |
+
<xslt:with-param name="caller" select="@id" />
|
159 |
+
<xslt:with-param name="is-a" select="@is-a" />
|
160 |
+
</xslt:call-template>
|
161 |
+
|
162 |
+
</xslt:template>
|
163 |
+
|
164 |
+
|
165 |
+
|
166 |
+
<!-- output everything else unchanged -->
|
167 |
+
<xslt:template match="*" priority="-1" mode="iae:go" >
|
168 |
+
<xslt:copy>
|
169 |
+
<xslt:copy-of select="@*" />
|
170 |
+
<xslt:apply-templates mode="iae:go"/>
|
171 |
+
</xslt:copy>
|
172 |
+
</xslt:template>
|
173 |
+
|
174 |
+
<!-- Templates for macro expansion of abstract patterns -->
|
175 |
+
<!-- Sets up the initial conditions for the recursive call -->
|
176 |
+
<xslt:template name="iae:macro-expand">
|
177 |
+
<xslt:param name="caller"/>
|
178 |
+
<xslt:param name="text" />
|
179 |
+
<xslt:call-template name="iae:multi-macro-expand">
|
180 |
+
<xslt:with-param name="caller" select="$caller"/>
|
181 |
+
<xslt:with-param name="text" select="$text"/>
|
182 |
+
<xslt:with-param name="paramNumber" select="1"/>
|
183 |
+
</xslt:call-template>
|
184 |
+
|
185 |
+
</xslt:template>
|
186 |
+
|
187 |
+
<!-- Template to replace the current parameter and then
|
188 |
+
recurse to replace subsequent parameters. -->
|
189 |
+
|
190 |
+
<xslt:template name="iae:multi-macro-expand">
|
191 |
+
<xslt:param name="caller"/>
|
192 |
+
<xslt:param name="text" />
|
193 |
+
<xslt:param name="paramNumber" />
|
194 |
+
|
195 |
+
|
196 |
+
<xslt:choose>
|
197 |
+
<xslt:when test="//iso:pattern[@id=$caller]/iso:param[ $paramNumber]">
|
198 |
+
|
199 |
+
<xslt:call-template name="iae:multi-macro-expand">
|
200 |
+
<xslt:with-param name="caller" select="$caller"/>
|
201 |
+
<xslt:with-param name="paramNumber" select="$paramNumber + 1"/>
|
202 |
+
<xslt:with-param name="text" >
|
203 |
+
<xslt:call-template name="iae:replace-substring">
|
204 |
+
<xslt:with-param name="original" select="$text"/>
|
205 |
+
<xslt:with-param name="substring"
|
206 |
+
select="concat('$', //iso:pattern[@id=$caller]/iso:param[ $paramNumber ]/@name)"/>
|
207 |
+
<xslt:with-param name="replacement"
|
208 |
+
select="//iso:pattern[@id=$caller]/iso:param[ $paramNumber ]/@value"/>
|
209 |
+
</xslt:call-template>
|
210 |
+
</xslt:with-param>
|
211 |
+
</xslt:call-template>
|
212 |
+
</xslt:when>
|
213 |
+
<xslt:otherwise><xslt:value-of select="$text" /></xslt:otherwise>
|
214 |
+
|
215 |
+
</xslt:choose>
|
216 |
+
</xslt:template>
|
217 |
+
|
218 |
+
|
219 |
+
<!-- generate the real pattern from an abstract pattern + parameters-->
|
220 |
+
<xslt:template name="iae:abstract-to-real" >
|
221 |
+
<xslt:param name="caller"/>
|
222 |
+
<xslt:param name="is-a" />
|
223 |
+
<xslt:for-each select="//iso:pattern[@id= $is-a]">
|
224 |
+
<xslt:copy>
|
225 |
+
|
226 |
+
<xslt:choose>
|
227 |
+
<xslt:when test=" string-length( $caller ) = 0">
|
228 |
+
<xslt:attribute name="id"><xslt:value-of select="concat( generate-id(.) , $is-a)" /></xslt:attribute>
|
229 |
+
</xslt:when>
|
230 |
+
<xslt:otherwise>
|
231 |
+
<xslt:attribute name="id"><xslt:value-of select="$caller" /></xslt:attribute>
|
232 |
+
</xslt:otherwise>
|
233 |
+
</xslt:choose>
|
234 |
+
|
235 |
+
<xslt:apply-templates select="*|text()" mode="iae:do-pattern" >
|
236 |
+
<xslt:with-param name="caller"><xslt:value-of select="$caller"/></xslt:with-param>
|
237 |
+
</xslt:apply-templates>
|
238 |
+
|
239 |
+
</xslt:copy>
|
240 |
+
</xslt:for-each>
|
241 |
+
</xslt:template>
|
242 |
+
|
243 |
+
|
244 |
+
<!-- Generate a non-abstract pattern -->
|
245 |
+
<xslt:template mode="iae:do-pattern" match="*">
|
246 |
+
<xslt:param name="caller"/>
|
247 |
+
<xslt:copy>
|
248 |
+
<xslt:for-each select="@*[name()='test' or name()='context' or name()='select' or name()='path' ]">
|
249 |
+
<xslt:attribute name="{name()}">
|
250 |
+
<xslt:call-template name="iae:macro-expand">
|
251 |
+
<xslt:with-param name="text"><xslt:value-of select="."/></xslt:with-param>
|
252 |
+
<xslt:with-param name="caller"><xslt:value-of select="$caller"/></xslt:with-param>
|
253 |
+
</xslt:call-template>
|
254 |
+
</xslt:attribute>
|
255 |
+
</xslt:for-each>
|
256 |
+
<xslt:copy-of select="@*[name()!='test'][name()!='context'][name()!='select'][name()!='path']" />
|
257 |
+
<xsl:for-each select="node()">
|
258 |
+
<xsl:choose>
|
259 |
+
<!-- Experiment: replace macros in text as well, to allow parameterized assertions
|
260 |
+
and so on, without having to have spurious <iso:value-of> calls and multiple
|
261 |
+
delimiting.
|
262 |
+
NOTE: THIS FUNCTIONALITY WILL BE REMOVED IN THE FUTURE -->
|
263 |
+
<xsl:when test="self::text()">
|
264 |
+
<xslt:call-template name="iae:macro-expand">
|
265 |
+
<xslt:with-param name="text"><xslt:value-of select="."/></xslt:with-param>
|
266 |
+
<xslt:with-param name="caller"><xslt:value-of select="$caller"/></xslt:with-param>
|
267 |
+
</xslt:call-template>
|
268 |
+
</xsl:when>
|
269 |
+
<xsl:otherwise>
|
270 |
+
<xslt:apply-templates select="." mode="iae:do-pattern">
|
271 |
+
<xslt:with-param name="caller"><xslt:value-of select="$caller"/></xslt:with-param>
|
272 |
+
</xslt:apply-templates>
|
273 |
+
</xsl:otherwise>
|
274 |
+
</xsl:choose>
|
275 |
+
</xsl:for-each>
|
276 |
+
</xslt:copy>
|
277 |
+
</xslt:template>
|
278 |
+
|
279 |
+
<!-- UTILITIES -->
|
280 |
+
<!-- Simple version of replace-substring function -->
|
281 |
+
<xslt:template name="iae:replace-substring">
|
282 |
+
<xslt:param name="original" />
|
283 |
+
<xslt:param name="substring" />
|
284 |
+
<xslt:param name="replacement" select="''"/>
|
285 |
+
|
286 |
+
<xsl:choose>
|
287 |
+
<xsl:when test="not($original)" />
|
288 |
+
<xsl:when test="not(string($substring))">
|
289 |
+
<xsl:value-of select="$original" />
|
290 |
+
</xsl:when>
|
291 |
+
<xsl:when test="contains($original, $substring)">
|
292 |
+
<xsl:variable name="before" select="substring-before($original, $substring)" />
|
293 |
+
<xsl:variable name="after" select="substring-after($original, $substring)" />
|
294 |
+
|
295 |
+
<xsl:value-of select="$before" />
|
296 |
+
<xsl:value-of select="$replacement" />
|
297 |
+
<!-- recursion -->
|
298 |
+
<xsl:call-template name="iae:replace-substring">
|
299 |
+
<xsl:with-param name="original" select="$after" />
|
300 |
+
<xsl:with-param name="substring" select="$substring" />
|
301 |
+
<xsl:with-param name="replacement" select="$replacement" />
|
302 |
+
</xsl:call-template>
|
303 |
+
</xsl:when>
|
304 |
+
<xsl:otherwise>
|
305 |
+
<!-- no substitution -->
|
306 |
+
<xsl:value-of select="$original" />
|
307 |
+
</xsl:otherwise>
|
308 |
+
</xsl:choose>
|
309 |
+
</xslt:template>
|
310 |
+
|
311 |
+
|
312 |
+
|
313 |
+
</xslt:stylesheet>
|
llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_dsdl_include.xsl
ADDED
@@ -0,0 +1,1160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<?xml version="1.0" encoding="UTF-8"?><?xar XSLT?>
|
2 |
+
|
3 |
+
<!--
|
4 |
+
OVERVIEW : iso_dsdl_include.xsl
|
5 |
+
|
6 |
+
This is an inclusion preprocessor for the non-smart text inclusions
|
7 |
+
of ISO DSDL. It handles
|
8 |
+
<relax:extRef> for ISO RELAX NG
|
9 |
+
<sch:include> for ISO Schematron and Schematron 1.n
|
10 |
+
<sch:extends> for 2009 draft ISO Schematron
|
11 |
+
<xi:xinclude> simple W3C XIncludes for ISO NVRL and DSRL
|
12 |
+
<crdl:ref> for draft ISO CRDL
|
13 |
+
<dtll:include> for draft ISO DTLL
|
14 |
+
<* @xlink:href> for simple W3C XLink 1.1 embedded links
|
15 |
+
|
16 |
+
|
17 |
+
This should be the first in any chain of processing. It only requires
|
18 |
+
XSLT 1. Each kind of inclusion can be turned off (or on) on the command line.
|
19 |
+
|
20 |
+
Ids in fragment identifiers or xpointers will be sought in the following
|
21 |
+
order:
|
22 |
+
* @xml:id
|
23 |
+
* id() for typed schemas (e.g. from DTD) [NOTE: XInclude does not support this]
|
24 |
+
* untyped @id
|
25 |
+
|
26 |
+
The proposed behaviour for the update to ISO Schematron has been implemented. If an
|
27 |
+
include points to an element with the same name as the parent, then that element's
|
28 |
+
contents will be included. This supports the merge style of inclusion.
|
29 |
+
|
30 |
+
When an inclusion is made, it is preceded by a PI with target DSDL_INCLUDE_START
|
31 |
+
and the href and closed by a PI with target DSDL_INCLUDE_START and the href. This is
|
32 |
+
to allow better location of problems, though only to the file level.
|
33 |
+
|
34 |
+
Limitations:
|
35 |
+
* No rebasing: relative paths will be interpreted based on the initial document's
|
36 |
+
path, not the including document. (Severe limitation!)
|
37 |
+
* No checking for circular references
|
38 |
+
* Not full xpointers: only ID matching
|
39 |
+
* <relax:include> not implemented
|
40 |
+
* XInclude handling of xml:base and xml:lang not implemented
|
41 |
+
-->
|
42 |
+
<!--
|
43 |
+
VERSION INFORMATION
|
44 |
+
2009-02-25
|
45 |
+
* Update DSDL namespace to use schematron.com
|
46 |
+
* Tested with SAXON9, Xalan 2.7.1, IE7,
|
47 |
+
* IE does not like multiple variables in same template with same name: rename.
|
48 |
+
2008-09-18
|
49 |
+
* Remove new behaviour for include, because it conflicts with existing usage [KH]
|
50 |
+
* Add extends[@href] element with that merge functionality
|
51 |
+
* Generate PIs to notate source of inclusions for potential better diagnostics
|
52 |
+
|
53 |
+
2008-09-16
|
54 |
+
* Fix for XSLT1
|
55 |
+
|
56 |
+
2008-08-28
|
57 |
+
* New behaviour for schematron includes: if the pointed to element is the same as the current,
|
58 |
+
include the children.
|
59 |
+
|
60 |
+
2008-08-20
|
61 |
+
* Fix bug: in XSLT1 cannot do $document/id('x') but need to use for-each
|
62 |
+
|
63 |
+
2008-08-04
|
64 |
+
* Add support for inclusions in old namespace
|
65 |
+
|
66 |
+
2008-08-03
|
67 |
+
* Fix wrong param name include-relaxng & include-crdl (KH, PH)
|
68 |
+
* Allow inclusion of XSLT and XHTML (KH)
|
69 |
+
* Fix inclusion of fragments (KH)
|
70 |
+
|
71 |
+
2008-07-25
|
72 |
+
* Add selectable input parameter
|
73 |
+
|
74 |
+
2008-07-24
|
75 |
+
* RJ New
|
76 |
+
-->
|
77 |
+
<!--
|
78 |
+
LEGAL INFORMATION
|
79 |
+
|
80 |
+
Copyright (c) 2008 Rick Jelliffe
|
81 |
+
|
82 |
+
This software is provided 'as-is', without any express or implied warranty.
|
83 |
+
In no event will the authors be held liable for any damages arising from
|
84 |
+
the use of this software.
|
85 |
+
|
86 |
+
Permission is granted to anyone to use this software for any purpose,
|
87 |
+
including commercial applications, and to alter it and redistribute it freely,
|
88 |
+
subject to the following restrictions:
|
89 |
+
|
90 |
+
1. The origin of this software must not be misrepresented; you must not claim
|
91 |
+
that you wrote the original software. If you use this software in a product,
|
92 |
+
an acknowledgment in the product documentation would be appreciated but is
|
93 |
+
not required.
|
94 |
+
|
95 |
+
2. Altered source versions must be plainly marked as such, and must not be
|
96 |
+
misrepresented as being the original software.
|
97 |
+
|
98 |
+
3. This notice may not be removed or altered from any source distribution.
|
99 |
+
-->
|
100 |
+
<xslt:stylesheet version="1.0"
|
101 |
+
xmlns:xslt="http://www.w3.org/1999/XSL/Transform"
|
102 |
+
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
|
103 |
+
xmlns:iso="http://purl.oclc.org/dsdl/schematron"
|
104 |
+
xmlns:nvdl="http://purl.oclc.org/dsdl/nvdl"
|
105 |
+
xmlns:xhtml="http://www.w3.org/1999/xhtml"
|
106 |
+
xmlns:schold="http://www.ascc.net/xml/schematron"
|
107 |
+
xmlns:crdl="http://purl.oclc.org/dsdl/crepdl/ns/structure/1.0"
|
108 |
+
xmlns:xi="http://www.w3.org/2001/XInclude"
|
109 |
+
xmlns:dtll="http://www.jenitennison.com/datatypes"
|
110 |
+
xmlns:dsdl="http://www.schematron.com/namespace/dsdl"
|
111 |
+
xmlns:relax="http://relaxng.org/ns/structure/1.0"
|
112 |
+
xmlns:xlink="http://www.w3.org/1999/xlink">
|
113 |
+
<!-- Note: The URL for the dsdl namespace is not official -->
|
114 |
+
|
115 |
+
|
116 |
+
<xsl:param name="include-schematron">true</xsl:param>
|
117 |
+
<xsl:param name="include-crdl">true</xsl:param>
|
118 |
+
<xsl:param name="include-xinclude">true</xsl:param>
|
119 |
+
<xsl:param name="include-dtll">true</xsl:param>
|
120 |
+
<xsl:param name="include-relaxng">true</xsl:param>
|
121 |
+
<xsl:param name="include-xlink">true</xsl:param>
|
122 |
+
|
123 |
+
<xsl:template match="/">
|
124 |
+
<xsl:apply-templates select="." mode="dsdl:go" />
|
125 |
+
</xsl:template>
|
126 |
+
|
127 |
+
<!-- output everything else unchanged -->
|
128 |
+
<xslt:template match="node()" priority="-1" mode="dsdl:go">
|
129 |
+
<xslt:copy>
|
130 |
+
<xslt:copy-of select="@*" />
|
131 |
+
<xslt:apply-templates mode="dsdl:go" />
|
132 |
+
</xslt:copy>
|
133 |
+
</xslt:template>
|
134 |
+
|
135 |
+
|
136 |
+
|
137 |
+
<!-- =========================================================== -->
|
138 |
+
<!-- ISO/IEC 19757 - DSDL Document Schema Definition Languages -->
|
139 |
+
<!-- Part 2 - Regular grammar-based validation - RELAX NG -->
|
140 |
+
<!-- This only implements relax:extRef not relax:include which -->
|
141 |
+
<!-- is complex. -->
|
142 |
+
<!-- =========================================================== -->
|
143 |
+
<xslt:template match="relax:extRef" mode="dsdl:go">
|
144 |
+
|
145 |
+
|
146 |
+
<!-- Insert subschema -->
|
147 |
+
|
148 |
+
<xsl:variable name="document-uri"
|
149 |
+
select="substring-before(concat(@href,'#'), '#')" />
|
150 |
+
<xsl:variable name="fragment-id"
|
151 |
+
select="substring-after(@href, '#')" />
|
152 |
+
|
153 |
+
<xsl:processing-instruction name="DSDL_INCLUDE_START">
|
154 |
+
<xsl:value-of select="@href" />
|
155 |
+
</xsl:processing-instruction>
|
156 |
+
<xsl:choose>
|
157 |
+
<xsl:when test="not( $include-relaxng = 'true' )">
|
158 |
+
<xslt:copy>
|
159 |
+
<xslt:copy-of select="@*" />
|
160 |
+
<xslt:apply-templates mode="dsdl:go" />
|
161 |
+
</xslt:copy>
|
162 |
+
</xsl:when>
|
163 |
+
<xsl:otherwise>
|
164 |
+
|
165 |
+
<xsl:choose>
|
166 |
+
|
167 |
+
<xsl:when
|
168 |
+
test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0">
|
169 |
+
<xsl:message>
|
170 |
+
Error: Impossible URL in RELAX NG extRef
|
171 |
+
include
|
172 |
+
</xsl:message>
|
173 |
+
</xsl:when>
|
174 |
+
|
175 |
+
<!-- this case is when there is in embedded schema in the same document elsewhere -->
|
176 |
+
<xslt:when
|
177 |
+
test="string-length( $document-uri ) = 0">
|
178 |
+
<xslt:apply-templates mode="dsdl:go"
|
179 |
+
select="//*[@xml:id= $fragment-id ] | id( $fragment-id) | //*[@id= $fragment-id ]" />
|
180 |
+
</xslt:when>
|
181 |
+
|
182 |
+
<xsl:when
|
183 |
+
test="string-length( $fragment-id ) > 0">
|
184 |
+
<xsl:variable name="theDocument_1"
|
185 |
+
select="document( $document-uri,/ )" />
|
186 |
+
|
187 |
+
<xsl:if test="not($theDocument_1)">
|
188 |
+
<xsl:message terminate="no">
|
189 |
+
<xsl:text>Unable to open referenced included file: </xsl:text>
|
190 |
+
<xsl:value-of select="@href" />
|
191 |
+
</xsl:message>
|
192 |
+
</xsl:if>
|
193 |
+
<!-- use a for-each so that the id() function works correctly on the external document -->
|
194 |
+
<xsl:for-each select="$theDocument_1">
|
195 |
+
<xsl:variable name="theFragment_1"
|
196 |
+
select="$theDocument_1//*[@xml:id= $fragment-id ]
|
197 |
+
| id( $fragment-id)
|
198 |
+
| $theDocument_1//*[@id= $fragment-id ]" />
|
199 |
+
<xsl:if test="not($theFragment_1)">
|
200 |
+
<xsl:message terminate="no">
|
201 |
+
<xsl:text>Unable to locate id attribute: </xsl:text>
|
202 |
+
<xsl:value-of select="@href" />
|
203 |
+
</xsl:message>
|
204 |
+
</xsl:if>
|
205 |
+
<xsl:apply-templates
|
206 |
+
select=" $theFragment_1[1]" mode="dsdl:go" />
|
207 |
+
</xsl:for-each>
|
208 |
+
</xsl:when>
|
209 |
+
|
210 |
+
<xsl:otherwise>
|
211 |
+
<xsl:variable name="theDocument_2"
|
212 |
+
select="document( $document-uri,/ )" />
|
213 |
+
<xsl:variable name="theFragment_2"
|
214 |
+
select="$theDocument_2/*" />
|
215 |
+
<xsl:if test="not($theDocument_2)">
|
216 |
+
<xsl:message terminate="no">
|
217 |
+
<xsl:text>Unable to open referenced included file: </xsl:text>
|
218 |
+
<xsl:value-of select="@href" />
|
219 |
+
</xsl:message>
|
220 |
+
</xsl:if>
|
221 |
+
|
222 |
+
<xsl:if test="not($theFragment_2)">
|
223 |
+
<xsl:message terminate="no">
|
224 |
+
<xsl:text>Unable to locate id attribute: </xsl:text>
|
225 |
+
<xsl:value-of select="@href" />
|
226 |
+
</xsl:message>
|
227 |
+
</xsl:if>
|
228 |
+
<xsl:apply-templates select="$theFragment_2 "
|
229 |
+
mode="dsdl:go" />
|
230 |
+
</xsl:otherwise>
|
231 |
+
</xsl:choose>
|
232 |
+
|
233 |
+
</xsl:otherwise>
|
234 |
+
</xsl:choose>
|
235 |
+
|
236 |
+
<xsl:processing-instruction name="DSDL_INCLUDE_END">
|
237 |
+
<xsl:value-of select="@href" />
|
238 |
+
</xsl:processing-instruction>
|
239 |
+
</xslt:template>
|
240 |
+
|
241 |
+
|
242 |
+
|
243 |
+
<!-- =========================================================== -->
|
244 |
+
<!-- ISO/IEC 19757 - DSDL Document Schema Definition Languages -->
|
245 |
+
<!-- Part 3 - Rule-based validation - Schematron -->
|
246 |
+
<!-- =========================================================== -->
|
247 |
+
|
248 |
+
|
249 |
+
<!-- Extend the URI syntax to allow # references -->
|
250 |
+
<!-- Add experimental support for simple containers like /xxx:xxx/iso:pattern to allow better includes -->
|
251 |
+
<xsl:template match="iso:include" mode="dsdl:go">
|
252 |
+
|
253 |
+
<xsl:variable name="document-uri"
|
254 |
+
select="substring-before(concat(@href,'#'), '#')" />
|
255 |
+
<xsl:variable name="fragment-id"
|
256 |
+
select="substring-after(@href, '#')" />
|
257 |
+
|
258 |
+
|
259 |
+
<xsl:processing-instruction name="DSDL_INCLUDE_START">
|
260 |
+
<xsl:value-of select="@href" />
|
261 |
+
</xsl:processing-instruction>
|
262 |
+
|
263 |
+
<xsl:choose>
|
264 |
+
<xsl:when test="not( $include-schematron = 'true' )">
|
265 |
+
<xslt:copy>
|
266 |
+
<xslt:copy-of select="@*" />
|
267 |
+
<xslt:apply-templates mode="dsdl:go" />
|
268 |
+
</xslt:copy>
|
269 |
+
</xsl:when>
|
270 |
+
<xsl:otherwise>
|
271 |
+
|
272 |
+
<xsl:choose>
|
273 |
+
|
274 |
+
<xsl:when
|
275 |
+
test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0">
|
276 |
+
<xsl:message>
|
277 |
+
Error: Impossible URL in Schematron include
|
278 |
+
</xsl:message>
|
279 |
+
</xsl:when>
|
280 |
+
|
281 |
+
<!-- this case is when there is in embedded schema in the same document elsewhere -->
|
282 |
+
<xslt:when
|
283 |
+
test="string-length( $document-uri ) = 0">
|
284 |
+
<xslt:apply-templates mode="dsdl:go"
|
285 |
+
select="//iso:*[@xml:id= $fragment-id ]
|
286 |
+
|id( $fragment-id)
|
287 |
+
| //iso:*[@id= $fragment-id ]" />
|
288 |
+
</xslt:when>
|
289 |
+
|
290 |
+
<!-- case where there is a fragment in another document (should be an iso: element) -->
|
291 |
+
<!-- There are three cases for includes with fragment:
|
292 |
+
0) No href file or no matching id - error!
|
293 |
+
1) REMOVED
|
294 |
+
|
295 |
+
2) The linked-to element is sch:schema however the parent of the include
|
296 |
+
is not a schema. In this case, it is an error. (Actually, it should
|
297 |
+
be an error for other kinds of containment problems, but we won't
|
298 |
+
check for them in this version.)
|
299 |
+
|
300 |
+
3) Otherwise, include the pointed-to element
|
301 |
+
-->
|
302 |
+
|
303 |
+
<xsl:when
|
304 |
+
test="string-length( $fragment-id ) > 0">
|
305 |
+
<xsl:variable name="theDocument_1"
|
306 |
+
select="document( $document-uri,/ )" />
|
307 |
+
<xsl:variable name="originalParent" select=".." />
|
308 |
+
|
309 |
+
<!-- case 0 -->
|
310 |
+
<xsl:if test="not($theDocument_1)">
|
311 |
+
<xsl:message terminate="no">
|
312 |
+
<xsl:text>Unable to open referenced included file: </xsl:text>
|
313 |
+
<xsl:value-of select="@href" />
|
314 |
+
</xsl:message>
|
315 |
+
</xsl:if>
|
316 |
+
<!-- use for-each to rebase id() to external document -->
|
317 |
+
<xsl:for-each select="$theDocument_1">
|
318 |
+
<xsl:variable name="theFragment_1"
|
319 |
+
select=" $theDocument_1//iso:*[@xml:id= $fragment-id ] |
|
320 |
+
id($fragment-id) |
|
321 |
+
$theDocument_1//iso:*[@id= $fragment-id ]" />
|
322 |
+
|
323 |
+
|
324 |
+
<xsl:choose>
|
325 |
+
<!-- case 0 -->
|
326 |
+
<xsl:when test="not($theFragment_1)">
|
327 |
+
<xsl:message terminate="no">
|
328 |
+
<xsl:text>Unable to locate id attribute: </xsl:text>
|
329 |
+
<xsl:value-of select="@href" />
|
330 |
+
</xsl:message>
|
331 |
+
</xsl:when>
|
332 |
+
|
333 |
+
|
334 |
+
<!-- case 1 REMOVED -->
|
335 |
+
|
336 |
+
<!-- case 2 -->
|
337 |
+
<xsl:when
|
338 |
+
test=" $theFragment_1/self::iso:schema ">
|
339 |
+
<xsl:message>
|
340 |
+
Schema error: Use include to
|
341 |
+
include fragments, not a whole
|
342 |
+
schema
|
343 |
+
</xsl:message>
|
344 |
+
</xsl:when>
|
345 |
+
|
346 |
+
<!-- case 3 -->
|
347 |
+
<xsl:otherwise>
|
348 |
+
<xsl:apply-templates
|
349 |
+
select=" $theFragment_1[1]" mode="dsdl:go" />
|
350 |
+
</xsl:otherwise>
|
351 |
+
</xsl:choose>
|
352 |
+
</xsl:for-each>
|
353 |
+
</xsl:when>
|
354 |
+
|
355 |
+
<!-- Case where there is no ID so we include the whole document -->
|
356 |
+
<!-- Experimental addition: include fragments of children -->
|
357 |
+
<xsl:otherwise>
|
358 |
+
<xsl:variable name="theDocument_2"
|
359 |
+
select="document( $document-uri,/ )" />
|
360 |
+
<xsl:variable name="theFragment_2"
|
361 |
+
select="$theDocument_2/iso:*" />
|
362 |
+
<xsl:variable name="theContainedFragments"
|
363 |
+
select="$theDocument_2/*/iso:* | $theDocument_2/*/xsl:* | $theDocument_2/*/xhtml:*" />
|
364 |
+
<xsl:if test="not($theDocument_2)">
|
365 |
+
<xsl:message terminate="no">
|
366 |
+
<xsl:text>Unable to open referenced included file: </xsl:text>
|
367 |
+
<xsl:value-of select="@href" />
|
368 |
+
</xsl:message>
|
369 |
+
</xsl:if>
|
370 |
+
|
371 |
+
<!-- There are three cases for includes:
|
372 |
+
0) No text specified- error!
|
373 |
+
|
374 |
+
1) REMOVED
|
375 |
+
|
376 |
+
2) The linked-to element is sch:schema however the parent of the include
|
377 |
+
is not a schema. In this case, it is an error. (Actually, it should
|
378 |
+
be an error for other kinds of containment problems, but we won't
|
379 |
+
check for them in this version.)
|
380 |
+
|
381 |
+
3) Otherwise, include the pointed-to element
|
382 |
+
-->
|
383 |
+
<xsl:choose>
|
384 |
+
<!-- case 0 -->
|
385 |
+
<xsl:when
|
386 |
+
test="not($theFragment_2) and not ($theContainedFragments)">
|
387 |
+
<xsl:message terminate="no">
|
388 |
+
<xsl:text>Unable to locate id attribute: </xsl:text>
|
389 |
+
<xsl:value-of select="@href" />
|
390 |
+
</xsl:message>
|
391 |
+
</xsl:when>
|
392 |
+
|
393 |
+
<!-- case 1 removed -->
|
394 |
+
|
395 |
+
<!-- case 2 -->
|
396 |
+
<xsl:when
|
397 |
+
test=" $theFragment_2/self::iso:schema or $theContainedFragments/self::iso:schema">
|
398 |
+
<xsl:message>
|
399 |
+
Schema error: Use include to include
|
400 |
+
fragments, not a whole schema
|
401 |
+
</xsl:message>
|
402 |
+
</xsl:when>
|
403 |
+
|
404 |
+
<!-- If this were XLST 2, we could use
|
405 |
+
if ($theFragment) then $theFragment else $theContainedFragments
|
406 |
+
here (thanks to KN)
|
407 |
+
-->
|
408 |
+
<!-- case 3 -->
|
409 |
+
<xsl:otherwise>
|
410 |
+
<xsl:apply-templates
|
411 |
+
select="$theFragment_2 " mode="dsdl:go" />
|
412 |
+
</xsl:otherwise>
|
413 |
+
</xsl:choose>
|
414 |
+
</xsl:otherwise>
|
415 |
+
</xsl:choose>
|
416 |
+
</xsl:otherwise>
|
417 |
+
</xsl:choose>
|
418 |
+
|
419 |
+
<xsl:processing-instruction name="DSDL_INCLUDE_END">
|
420 |
+
<xsl:value-of select="@href" />
|
421 |
+
</xsl:processing-instruction>
|
422 |
+
</xsl:template>
|
423 |
+
|
424 |
+
|
425 |
+
<!-- WARNING sch:extends[@href] is experimental and non standard -->
|
426 |
+
<!-- Basically, it adds the children of the selected element, not the element itself. -->
|
427 |
+
<xsl:template match="iso:extends[@href]" mode="dsdl:go">
|
428 |
+
|
429 |
+
<xsl:variable name="document-uri"
|
430 |
+
select="substring-before(concat(@href,'#'), '#')" />
|
431 |
+
<xsl:variable name="fragment-id"
|
432 |
+
select="substring-after(@href, '#')" />
|
433 |
+
|
434 |
+
|
435 |
+
<xsl:processing-instruction name="DSDL_INCLUDE_START">
|
436 |
+
<xsl:value-of select="@href" />
|
437 |
+
</xsl:processing-instruction>
|
438 |
+
|
439 |
+
<xsl:choose>
|
440 |
+
<xsl:when test="not( $include-schematron = 'true' )">
|
441 |
+
<xslt:copy>
|
442 |
+
<xslt:copy-of select="@*" />
|
443 |
+
<xslt:apply-templates mode="dsdl:go" />
|
444 |
+
</xslt:copy>
|
445 |
+
</xsl:when>
|
446 |
+
<xsl:otherwise>
|
447 |
+
|
448 |
+
<xsl:choose>
|
449 |
+
|
450 |
+
<xsl:when
|
451 |
+
test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0">
|
452 |
+
<xsl:message>
|
453 |
+
Error: Impossible URL in Schematron include
|
454 |
+
</xsl:message>
|
455 |
+
</xsl:when>
|
456 |
+
|
457 |
+
<!-- this case is when there is in embedded schema in the same document elsewhere -->
|
458 |
+
<xslt:when
|
459 |
+
test="string-length( $document-uri ) = 0">
|
460 |
+
<xslt:apply-templates mode="dsdl:go"
|
461 |
+
select="//iso:*[@xml:id= $fragment-id ]/*
|
462 |
+
|id( $fragment-id)/*
|
463 |
+
| //iso:*[@id= $fragment-id ]/*" />
|
464 |
+
</xslt:when>
|
465 |
+
|
466 |
+
<!-- case where there is a fragment in another document (should be an iso: element) -->
|
467 |
+
<!-- There are three cases for includes with fragment:
|
468 |
+
0) No href file or no matching id - error!
|
469 |
+
1) REMOVED
|
470 |
+
|
471 |
+
2) REMOVED
|
472 |
+
|
473 |
+
3) Otherwise, include the pointed-to element
|
474 |
+
-->
|
475 |
+
|
476 |
+
<xsl:when
|
477 |
+
test="string-length( $fragment-id ) > 0">
|
478 |
+
<xsl:variable name="theDocument_1"
|
479 |
+
select="document( $document-uri,/ )" />
|
480 |
+
<xsl:variable name="originalParent" select=".." />
|
481 |
+
|
482 |
+
<!-- case 0 -->
|
483 |
+
<xsl:if test="not($theDocument_1)">
|
484 |
+
<xsl:message terminate="no">
|
485 |
+
<xsl:text>Unable to open referenced included file: </xsl:text>
|
486 |
+
<xsl:value-of select="@href" />
|
487 |
+
</xsl:message>
|
488 |
+
</xsl:if>
|
489 |
+
<!-- use for-each to rebase id() to external document -->
|
490 |
+
<xsl:for-each select="$theDocument_1">
|
491 |
+
<xsl:variable name="theFragment_1"
|
492 |
+
select=" $theDocument_1//iso:*[@xml:id= $fragment-id ] |
|
493 |
+
id($fragment-id) |
|
494 |
+
$theDocument_1//iso:*[@id= $fragment-id ]" />
|
495 |
+
|
496 |
+
|
497 |
+
<xsl:choose>
|
498 |
+
<!-- case 0 -->
|
499 |
+
<xsl:when test="not($theFragment_1)">
|
500 |
+
<xsl:message terminate="no">
|
501 |
+
<xsl:text>Unable to locate id attribute: </xsl:text>
|
502 |
+
<xsl:value-of select="@href" />
|
503 |
+
</xsl:message>
|
504 |
+
</xsl:when>
|
505 |
+
|
506 |
+
|
507 |
+
<!-- case 1 REMOVED -->
|
508 |
+
|
509 |
+
<!-- case 2 REMOVED -->
|
510 |
+
|
511 |
+
|
512 |
+
<!-- case 3 -->
|
513 |
+
<xsl:otherwise>
|
514 |
+
|
515 |
+
<xsl:apply-templates
|
516 |
+
select=" $theFragment_1[1]/*" mode="dsdl:go" />
|
517 |
+
</xsl:otherwise>
|
518 |
+
</xsl:choose>
|
519 |
+
</xsl:for-each>
|
520 |
+
</xsl:when>
|
521 |
+
|
522 |
+
<!-- Case where there is no ID so we include the whole document -->
|
523 |
+
<!-- Experimental addition: include fragments of children -->
|
524 |
+
<xsl:otherwise>
|
525 |
+
<xsl:variable name="theDocument_2"
|
526 |
+
select="document( $document-uri,/ )" />
|
527 |
+
<xsl:variable name="theFragment_2"
|
528 |
+
select="$theDocument_2/iso:*" />
|
529 |
+
<xsl:variable name="theContainedFragments"
|
530 |
+
select="$theDocument_2/*/iso:* | $theDocument_2/*/xsl:* | $theDocument_2/*/xhtml:*" />
|
531 |
+
<xsl:if test="not($theDocument_2)">
|
532 |
+
<xsl:message terminate="no">
|
533 |
+
<xsl:text>Unable to open referenced included file: </xsl:text>
|
534 |
+
<xsl:value-of select="@href" />
|
535 |
+
</xsl:message>
|
536 |
+
</xsl:if>
|
537 |
+
|
538 |
+
<!-- There are three cases for includes:
|
539 |
+
0) No text specified- error!
|
540 |
+
|
541 |
+
1) REMOVED
|
542 |
+
|
543 |
+
2) REMOVED
|
544 |
+
|
545 |
+
3) Otherwise, include the pointed-to element
|
546 |
+
-->
|
547 |
+
<xsl:choose>
|
548 |
+
<!-- case 0 -->
|
549 |
+
<xsl:when
|
550 |
+
test="not($theFragment_2) and not ($theContainedFragments)">
|
551 |
+
<xsl:message terminate="no">
|
552 |
+
<xsl:text>Unable to locate id attribute: </xsl:text>
|
553 |
+
<xsl:value-of select="@href" />
|
554 |
+
</xsl:message>
|
555 |
+
</xsl:when>
|
556 |
+
|
557 |
+
<!-- case 1 removed -->
|
558 |
+
|
559 |
+
<!-- case 2 removed -->
|
560 |
+
|
561 |
+
<!-- If this were XLST 2, we could use
|
562 |
+
if ($theFragment) then $theFragment else $theContainedFragments
|
563 |
+
here (thanks to KN)
|
564 |
+
-->
|
565 |
+
<!-- case 3 -->
|
566 |
+
<xsl:otherwise>
|
567 |
+
<xsl:apply-templates
|
568 |
+
select="$theFragment_2/* " mode="dsdl:go" />
|
569 |
+
</xsl:otherwise>
|
570 |
+
</xsl:choose>
|
571 |
+
</xsl:otherwise>
|
572 |
+
</xsl:choose>
|
573 |
+
</xsl:otherwise>
|
574 |
+
</xsl:choose>
|
575 |
+
|
576 |
+
<xsl:processing-instruction name="DSDL_INCLUDE_END">
|
577 |
+
<xsl:value-of select="@href" />
|
578 |
+
</xsl:processing-instruction>
|
579 |
+
</xsl:template>
|
580 |
+
|
581 |
+
|
582 |
+
|
583 |
+
<!-- =========================================================== -->
|
584 |
+
<!-- Handle Schematron 1.6 inclusions: clone of ISO code above -->
|
585 |
+
<!-- =========================================================== -->
|
586 |
+
|
587 |
+
|
588 |
+
<!-- Extend the URI syntax to allow # references -->
|
589 |
+
<!-- Add experimental support for simple containers like /xxx:xxx/schold:pattern to allow better includes -->
|
590 |
+
<xsl:template match="schold:include" mode="dsdl:go">
|
591 |
+
<xsl:variable name="document-uri"
|
592 |
+
select="substring-before(concat(@href,'#'), '#')" />
|
593 |
+
<xsl:variable name="fragment-id"
|
594 |
+
select="substring-after(@href, '#')" />
|
595 |
+
|
596 |
+
<xsl:processing-instruction name="DSDL_INCLUDE_START">
|
597 |
+
<xsl:value-of select="@href" />
|
598 |
+
</xsl:processing-instruction>
|
599 |
+
|
600 |
+
<xsl:choose>
|
601 |
+
<xsl:when test="not( $include-schematron = 'true' )">
|
602 |
+
<xslt:copy>
|
603 |
+
<xslt:copy-of select="@*" />
|
604 |
+
<xslt:apply-templates mode="dsdl:go" />
|
605 |
+
</xslt:copy>
|
606 |
+
</xsl:when>
|
607 |
+
<xsl:otherwise>
|
608 |
+
<xsl:choose>
|
609 |
+
|
610 |
+
<xsl:when
|
611 |
+
test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0">
|
612 |
+
<xsl:message>
|
613 |
+
Error: Impossible URL in Schematron include
|
614 |
+
</xsl:message>
|
615 |
+
</xsl:when>
|
616 |
+
|
617 |
+
<!-- this case is when there is in embedded schema in the same document elsewhere -->
|
618 |
+
<xslt:when
|
619 |
+
test="string-length( $document-uri ) = 0">
|
620 |
+
<xslt:apply-templates mode="dsdl:go"
|
621 |
+
select="//schold:*[@xml:id= $fragment-id ]
|
622 |
+
|id( $fragment-id)
|
623 |
+
| //schold:*[@id= $fragment-id ]" />
|
624 |
+
</xslt:when>
|
625 |
+
|
626 |
+
<!-- case where there is a fragment in another document (should be an iso: element) -->
|
627 |
+
<xsl:when
|
628 |
+
test="string-length( $fragment-id ) > 0">
|
629 |
+
<xsl:variable name="theDocument_1"
|
630 |
+
select="document( $document-uri,/ )" />
|
631 |
+
<xsl:if test="not($theDocument_1)">
|
632 |
+
<xsl:message terminate="no">
|
633 |
+
<xsl:text>Unable to open referenced included file: </xsl:text>
|
634 |
+
<xsl:value-of select="@href" />
|
635 |
+
</xsl:message>
|
636 |
+
</xsl:if>
|
637 |
+
<!-- use for-each to rebase id() to $theDocument -->
|
638 |
+
<xsl:for-each select="$theDocument_1">
|
639 |
+
<xsl:variable name="theFragment_1"
|
640 |
+
select=" $theDocument_1//schold:*[@xml:id= $fragment-id ] |
|
641 |
+
id($fragment-id) |
|
642 |
+
$theDocument_1//schold:*[@id= $fragment-id ]" />
|
643 |
+
<xsl:if
|
644 |
+
test=" $theFragment_1/self::schold:schema ">
|
645 |
+
<xsl:message>
|
646 |
+
Schema error: Use include to include
|
647 |
+
fragments, not a whole schema
|
648 |
+
</xsl:message>
|
649 |
+
</xsl:if>
|
650 |
+
<xsl:if test="not($theFragment_1)">
|
651 |
+
<xsl:message terminate="no">
|
652 |
+
<xsl:text>Unable to locate id attribute: </xsl:text>
|
653 |
+
<xsl:value-of select="@href" />
|
654 |
+
</xsl:message>
|
655 |
+
</xsl:if>
|
656 |
+
<xsl:apply-templates
|
657 |
+
select=" $theFragment_1[1]" mode="dsdl:go" />
|
658 |
+
</xsl:for-each>
|
659 |
+
</xsl:when>
|
660 |
+
|
661 |
+
<!-- Case where there is no ID so we include the whole document -->
|
662 |
+
<!-- Experimental addition: include fragments of children -->
|
663 |
+
<xsl:otherwise>
|
664 |
+
<xsl:variable name="theDocument_2"
|
665 |
+
select="document( $document-uri,/ )" />
|
666 |
+
<xsl:variable name="theFragment_2"
|
667 |
+
select="$theDocument_2/iso:*" />
|
668 |
+
<xsl:variable name="theContainedFragments"
|
669 |
+
select="$theDocument_2/*/schold:* | $theDocument_2/*/xsl:* | $theDocument_2/*/xhtml:*" />
|
670 |
+
<xsl:if test="not($theDocument_2)">
|
671 |
+
<xsl:message terminate="no">
|
672 |
+
<xsl:text>Unable to open referenced included file: </xsl:text>
|
673 |
+
<xsl:value-of select="@href" />
|
674 |
+
</xsl:message>
|
675 |
+
</xsl:if>
|
676 |
+
|
677 |
+
<xsl:if
|
678 |
+
test=" $theFragment_2/self::schold:schema or $theContainedFragments/self::schold:schema">
|
679 |
+
<xsl:message>
|
680 |
+
Schema error: Use include to include
|
681 |
+
fragments, not a whole schema
|
682 |
+
</xsl:message>
|
683 |
+
</xsl:if>
|
684 |
+
<xsl:if
|
685 |
+
test="not($theFragment_2) and not ($theContainedFragments)">
|
686 |
+
<xsl:message terminate="no">
|
687 |
+
<xsl:text>Unable to locate id attribute: </xsl:text>
|
688 |
+
<xsl:value-of select="@href" />
|
689 |
+
</xsl:message>
|
690 |
+
</xsl:if>
|
691 |
+
<!-- If this were XLST 2, we could use
|
692 |
+
if ($theFragment) then $theFragment else $theContainedFragments
|
693 |
+
here (thanks to KN)
|
694 |
+
-->
|
695 |
+
<xsl:choose>
|
696 |
+
<xsl:when test=" $theFragment_2 ">
|
697 |
+
<xsl:apply-templates
|
698 |
+
select="$theFragment_2 " mode="dsdl:go" />
|
699 |
+
</xsl:when>
|
700 |
+
<xsl:otherwise>
|
701 |
+
<!-- WARNING! EXPERIMENTAL! Use at your own risk. This may be discontinued! -->
|
702 |
+
<xsl:apply-templates
|
703 |
+
select=" $theContainedFragments " mode="dsdl:go" />
|
704 |
+
</xsl:otherwise>
|
705 |
+
</xsl:choose>
|
706 |
+
</xsl:otherwise>
|
707 |
+
</xsl:choose>
|
708 |
+
|
709 |
+
</xsl:otherwise>
|
710 |
+
</xsl:choose>
|
711 |
+
|
712 |
+
<xsl:processing-instruction name="DSDL_INCLUDE_END">
|
713 |
+
<xsl:value-of select="@href" />
|
714 |
+
</xsl:processing-instruction>
|
715 |
+
</xsl:template>
|
716 |
+
<!-- =========================================================== -->
|
717 |
+
<!-- ISO/IEC 19757 - DSDL Document Schema Definition Languages -->
|
718 |
+
<!-- Part 5 - DataType Library Language - DTLL -->
|
719 |
+
<!-- Committee Draft Experimental support only -->
|
720 |
+
<!-- The <include> element may well be replaced by XInclude in -->
|
721 |
+
<!-- any final version. -->
|
722 |
+
<!-- =========================================================== -->
|
723 |
+
<xslt:template match="dtll:include" mode="dsdl:go">
|
724 |
+
<!-- Insert subschema -->
|
725 |
+
|
726 |
+
<xsl:variable name="document-uri"
|
727 |
+
select="substring-before(concat(@href,'#'), '#')" />
|
728 |
+
<xsl:variable name="fragment-id"
|
729 |
+
select="substring-after(@href, '#')" />
|
730 |
+
<xsl:processing-instruction name="DSDL_INCLUDE_START">
|
731 |
+
<xsl:value-of select="@href" />
|
732 |
+
</xsl:processing-instruction>
|
733 |
+
<xsl:choose>
|
734 |
+
<xsl:when test="not( $include-dtll = 'true' )">
|
735 |
+
<xslt:copy>
|
736 |
+
<xslt:copy-of select="@*" />
|
737 |
+
<xslt:apply-templates mode="dsdl:go" />
|
738 |
+
</xslt:copy>
|
739 |
+
</xsl:when>
|
740 |
+
<xsl:otherwise>
|
741 |
+
<xsl:choose>
|
742 |
+
|
743 |
+
<xsl:when
|
744 |
+
test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0">
|
745 |
+
<xsl:message>
|
746 |
+
Error: Impossible URL in DTLL include
|
747 |
+
</xsl:message>
|
748 |
+
</xsl:when>
|
749 |
+
|
750 |
+
<!-- this case is when there is in embedded schema in the same document elsewhere -->
|
751 |
+
<xslt:when
|
752 |
+
test="string-length( $document-uri ) = 0">
|
753 |
+
<xslt:apply-templates mode="dsdl:go"
|
754 |
+
select="//*[@xml:id= $fragment-id ] | id( $fragment-id)
|
755 |
+
| //*[@id= $fragment-id ]" />
|
756 |
+
</xslt:when>
|
757 |
+
|
758 |
+
<xsl:when
|
759 |
+
test="string-length( $fragment-id ) > 0">
|
760 |
+
<xsl:variable name="theDocument_1"
|
761 |
+
select="document( $document-uri,/ )" />
|
762 |
+
<xsl:if test="not($theDocument_1)">
|
763 |
+
<xsl:message terminate="no">
|
764 |
+
<xsl:text>Unable to open referenced included file: </xsl:text>
|
765 |
+
<xsl:value-of select="@href" />
|
766 |
+
</xsl:message>
|
767 |
+
</xsl:if>
|
768 |
+
<!-- use for-each to rebase id() to $theDocument -->
|
769 |
+
<xsl:for-each select="$theDocument_1">
|
770 |
+
<xsl:variable name="theFragment_1"
|
771 |
+
select="$theDocument_1//*[@xml:id= $fragment-id ]
|
772 |
+
| id( $fragment-id )
|
773 |
+
| $theDocument_1//*[@id= $fragment-id ]" />
|
774 |
+
<xsl:if test="not($theFragment_1)">
|
775 |
+
<xsl:message terminate="no">
|
776 |
+
<xsl:text>Unable to locate id attribute: </xsl:text>
|
777 |
+
<xsl:value-of select="@href" />
|
778 |
+
</xsl:message>
|
779 |
+
</xsl:if>
|
780 |
+
<xsl:apply-templates
|
781 |
+
select=" $theFragment_1[1]" mode="dsdl:go" />
|
782 |
+
</xsl:for-each>
|
783 |
+
</xsl:when>
|
784 |
+
|
785 |
+
<xsl:otherwise>
|
786 |
+
<xsl:variable name="theDocument_2"
|
787 |
+
select="document( $document-uri,/ )" />
|
788 |
+
<xsl:variable name="theFragment_2"
|
789 |
+
select="$theDocument_2/*" />
|
790 |
+
|
791 |
+
<xsl:if test="not($theDocument_2)">
|
792 |
+
<xsl:message terminate="no">
|
793 |
+
<xsl:text>Unable to open referenced included file: </xsl:text>
|
794 |
+
<xsl:value-of select="@href" />
|
795 |
+
</xsl:message>
|
796 |
+
</xsl:if>
|
797 |
+
|
798 |
+
<xsl:if test="not($theFragment_2)">
|
799 |
+
<xsl:message terminate="no">
|
800 |
+
<xsl:text>Unable to locate id attribute: </xsl:text>
|
801 |
+
<xsl:value-of select="@href" />
|
802 |
+
</xsl:message>
|
803 |
+
</xsl:if>
|
804 |
+
<xsl:apply-templates select="$theFragment_2 "
|
805 |
+
mode="dsdl:go" />
|
806 |
+
</xsl:otherwise>
|
807 |
+
</xsl:choose>
|
808 |
+
|
809 |
+
</xsl:otherwise>
|
810 |
+
</xsl:choose>
|
811 |
+
<xsl:processing-instruction name="DSDL_INCLUDE_END">
|
812 |
+
<xsl:value-of select="@href" />
|
813 |
+
</xsl:processing-instruction>
|
814 |
+
</xslt:template>
|
815 |
+
|
816 |
+
<!-- =========================================================== -->
|
817 |
+
<!-- ISO/IEC 19757 - DSDL Document Schema Definition Languages -->
|
818 |
+
<!-- Part 7 - Character Repertoire Description Language - CRDL -->
|
819 |
+
<!-- Final Committee Draft 2008-01-11 Experimental support only -->
|
820 |
+
<!-- =========================================================== -->
|
821 |
+
<xslt:template match="crdl:ref" mode="dsdl:go">
|
822 |
+
<!-- Insert subschema -->
|
823 |
+
|
824 |
+
<xsl:variable name="document-uri"
|
825 |
+
select="substring-before(concat(@href,'#'), '#')" />
|
826 |
+
<xsl:variable name="fragment-id"
|
827 |
+
select="substring-after(@href, '#')" />
|
828 |
+
<xsl:processing-instruction name="DSDL_INCLUDE_START">
|
829 |
+
<xsl:value-of select="@href" />
|
830 |
+
</xsl:processing-instruction>
|
831 |
+
<xsl:choose>
|
832 |
+
<xsl:when test="not( $include-crdl = 'true' )">
|
833 |
+
<xslt:copy>
|
834 |
+
<xslt:copy-of select="@*" />
|
835 |
+
<xslt:apply-templates mode="dsdl:go" />
|
836 |
+
</xslt:copy>
|
837 |
+
</xsl:when>
|
838 |
+
<xsl:otherwise>
|
839 |
+
<xsl:choose>
|
840 |
+
|
841 |
+
<xsl:when
|
842 |
+
test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0">
|
843 |
+
<xsl:message>
|
844 |
+
Error: Impossible URL in CRDL include
|
845 |
+
</xsl:message>
|
846 |
+
</xsl:when>
|
847 |
+
|
848 |
+
<!-- this case is when there is in embedded schema in the same document elsewhere -->
|
849 |
+
<xslt:when
|
850 |
+
test="string-length( $document-uri ) = 0">
|
851 |
+
|
852 |
+
<xslt:apply-templates mode="dsdl:go"
|
853 |
+
select="//*[@xml:id= $fragment-id ] | id( $fragment-id)
|
854 |
+
| //*[@id= $fragment-id ]" />
|
855 |
+
</xslt:when>
|
856 |
+
|
857 |
+
<xsl:when
|
858 |
+
test="string-length( $fragment-id ) > 0">
|
859 |
+
<xsl:variable name="theDocument_1"
|
860 |
+
select="document( $document-uri,/ )" />
|
861 |
+
<xsl:if test="not($theDocument_1)">
|
862 |
+
<xsl:message terminate="no">
|
863 |
+
<xsl:text>Unable to open referenced included file: </xsl:text>
|
864 |
+
<xsl:value-of select="@href" />
|
865 |
+
</xsl:message>
|
866 |
+
</xsl:if>
|
867 |
+
<!-- use for-each to rebase id() to $theDocument -->
|
868 |
+
<xsl:for-each select="$theDocument_1">
|
869 |
+
<xsl:variable name="theFragment_1"
|
870 |
+
select="$theDocument_1//*[@xml:id= $fragment-id ]
|
871 |
+
| id( $fragment-id )
|
872 |
+
| $theDocument_1//*[@id= $fragment-id ]" />
|
873 |
+
|
874 |
+
<xsl:if test="not($theFragment_1)">
|
875 |
+
<xsl:message terminate="no">
|
876 |
+
<xsl:text>Unable to locate id attribute: </xsl:text>
|
877 |
+
<xsl:value-of select="@href" />
|
878 |
+
</xsl:message>
|
879 |
+
</xsl:if>
|
880 |
+
<xsl:apply-templates select=" $theFragment_1 "
|
881 |
+
mode="dsdl:go" />
|
882 |
+
</xsl:for-each>
|
883 |
+
</xsl:when>
|
884 |
+
|
885 |
+
<xsl:otherwise>
|
886 |
+
<xsl:variable name="theDocument_2"
|
887 |
+
select="document( $document-uri,/ )" />
|
888 |
+
<xsl:variable name="theFragment_2"
|
889 |
+
select="$theDocument_2/*" />
|
890 |
+
|
891 |
+
<xsl:if test="not($theDocument_2)">
|
892 |
+
<xsl:message terminate="no">
|
893 |
+
<xsl:text>Unable to open referenced included file: </xsl:text>
|
894 |
+
<xsl:value-of select="@href" />
|
895 |
+
</xsl:message>
|
896 |
+
</xsl:if>
|
897 |
+
<xsl:if test="not($theFragment_2)">
|
898 |
+
<xsl:message terminate="no">
|
899 |
+
<xsl:text>Unable to locate id attribute: </xsl:text>
|
900 |
+
<xsl:value-of select="@href" />
|
901 |
+
</xsl:message>
|
902 |
+
</xsl:if>
|
903 |
+
|
904 |
+
<xsl:apply-templates select="$theFragment_2"
|
905 |
+
mode="dsdl:go" />
|
906 |
+
</xsl:otherwise>
|
907 |
+
</xsl:choose>
|
908 |
+
|
909 |
+
</xsl:otherwise>
|
910 |
+
</xsl:choose>
|
911 |
+
<xsl:processing-instruction name="DSDL_INCLUDE_END">
|
912 |
+
<xsl:value-of select="@href" />
|
913 |
+
</xsl:processing-instruction>
|
914 |
+
</xslt:template>
|
915 |
+
|
916 |
+
|
917 |
+
<!-- =========================================================== -->
|
918 |
+
<!-- ISO/IEC 19757 - DSDL Document Schema Definition Languages -->
|
919 |
+
<!-- Part 4 - Namespace-based Validation Dispatching Language - NVDL -->
|
920 |
+
<!-- Note: This does not include schemas referenced for -->
|
921 |
+
<!-- validation, it merely handles any simple XIncludes -->
|
922 |
+
<!-- =========================================================== -->
|
923 |
+
<!-- ISO/IEC 19757 - DSDL Document Schema Definition Languages -->
|
924 |
+
<!-- Part 8 - Document Schema Renaming Language - DSRL -->
|
925 |
+
<!-- Note: Final? Committee Draft Experimental support only -->
|
926 |
+
<!-- =========================================================== -->
|
927 |
+
<!-- XInclude support for id based references only, with 1 level -->
|
928 |
+
<!-- of fallback. -->
|
929 |
+
<!-- =========================================================== -->
|
930 |
+
|
931 |
+
<xslt:template mode="dsdl:go"
|
932 |
+
match="xi:include[@href][not(@parseType) or @parseType ='xml']">
|
933 |
+
<!-- Simple inclusions only here -->
|
934 |
+
<xsl:processing-instruction name="DSDL_INCLUDE_START">
|
935 |
+
<xsl:value-of select="@href" />
|
936 |
+
</xsl:processing-instruction>
|
937 |
+
<xsl:choose>
|
938 |
+
<xsl:when test="not( $include-xinclude = 'true' )">
|
939 |
+
<xslt:copy>
|
940 |
+
<xslt:copy-of select="@*" />
|
941 |
+
<xslt:apply-templates mode="dsdl:go" />
|
942 |
+
</xslt:copy>
|
943 |
+
</xsl:when>
|
944 |
+
<xsl:otherwise>
|
945 |
+
<xsl:choose>
|
946 |
+
|
947 |
+
<xsl:when test="contains( @href, '#')">
|
948 |
+
<xsl:message terminate="yes">
|
949 |
+
Fatal error: Xinclude href contains fragment
|
950 |
+
identifier #
|
951 |
+
</xsl:message>
|
952 |
+
</xsl:when>
|
953 |
+
|
954 |
+
|
955 |
+
<xsl:when test="contains( @xpointer, '(')">
|
956 |
+
<xsl:message terminate="yes">
|
957 |
+
Fatal error: Sorry, this software only
|
958 |
+
supports simple ids in XInclude xpointers
|
959 |
+
</xsl:message>
|
960 |
+
</xsl:when>
|
961 |
+
|
962 |
+
<xsl:when
|
963 |
+
test="string-length( @href ) = 0 and string-length( @xpointer ) = 0">
|
964 |
+
|
965 |
+
<xsl:message terminate="yes">
|
966 |
+
Fatal Error: Impossible URL in XInclude
|
967 |
+
include
|
968 |
+
</xsl:message>
|
969 |
+
</xsl:when>
|
970 |
+
|
971 |
+
<!-- this case is when there is in embedded schema in the same document elsewhere -->
|
972 |
+
<xslt:when test="string-length( @href ) = 0">
|
973 |
+
|
974 |
+
<xslt:apply-templates mode="dsdl:go"
|
975 |
+
select="//*[@xml:id= current()/@xpointer ] | id( @xpointer)
|
976 |
+
| //*[@id= current()/@xpointer ]" />
|
977 |
+
</xslt:when>
|
978 |
+
|
979 |
+
<xsl:when
|
980 |
+
test="string-length( @xpointer ) > 0">
|
981 |
+
<xsl:variable name="theDocument_1"
|
982 |
+
select="document( @href,/ )" />
|
983 |
+
<xsl:variable name="theFragment_1"
|
984 |
+
select="$theDocument_1//*[@xml:id= current()/@xpointer ]
|
985 |
+
|
986 |
+
| $theDocument_1//*[@id= current()/@xpointer ]" />
|
987 |
+
<!-- removed
|
988 |
+
| $theDocument_1/id( @xpointer)
|
989 |
+
because it requires rebasing in XSLT1 and that would mess up the use of current()
|
990 |
+
-->
|
991 |
+
|
992 |
+
|
993 |
+
<!-- Allow one level of fallback, to another XInclude -->
|
994 |
+
<xsl:if test="not($theDocument_1)">
|
995 |
+
<xsl:choose>
|
996 |
+
<xsl:when test="xi:fallback">
|
997 |
+
<xsl:variable name="theDocument_2"
|
998 |
+
select="document( xi:fallback[1]/xi:include[not(@parseType)
|
999 |
+
or @parseType='xml']/@href,/ )" />
|
1000 |
+
<xsl:variable name="theFragment_2"
|
1001 |
+
select="$theDocument_2//*[@xml:id= current()/xi:fallback[1]/xi:include/@xpointer ]
|
1002 |
+
| $theDocument_2//*[@id= current()/xi:fallback[1]/xi:include/@xpointer ]" />
|
1003 |
+
<!-- removed
|
1004 |
+
| $theDocument_2/id( xi:fallback[1]/xi:include/@xpointer)
|
1005 |
+
because it id() would need rebasing in XSLT1 and that would mess up use of current()
|
1006 |
+
-->
|
1007 |
+
|
1008 |
+
<xsl:if
|
1009 |
+
test="not($theDocument_2)">
|
1010 |
+
|
1011 |
+
<xsl:message terminate="no">
|
1012 |
+
<xsl:text>Unable to open referenced included file and fallback
|
1013 |
+
file: </xsl:text>
|
1014 |
+
<xsl:value-of
|
1015 |
+
select="@href" />
|
1016 |
+
</xsl:message>
|
1017 |
+
</xsl:if>
|
1018 |
+
</xsl:when>
|
1019 |
+
<xsl:otherwise>
|
1020 |
+
<xsl:message terminate="no">
|
1021 |
+
<xsl:text>Unable to open referenced included file: </xsl:text>
|
1022 |
+
<xsl:value-of select="@href" />
|
1023 |
+
</xsl:message>
|
1024 |
+
</xsl:otherwise>
|
1025 |
+
</xsl:choose>
|
1026 |
+
</xsl:if>
|
1027 |
+
<xsl:apply-templates select=" $theFragment_1"
|
1028 |
+
mode="dsdl:go" />
|
1029 |
+
</xsl:when>
|
1030 |
+
|
1031 |
+
<!-- Document but no fragment specified -->
|
1032 |
+
<xsl:otherwise>
|
1033 |
+
<xsl:variable name="theDocument_3"
|
1034 |
+
select="document( @href,/ )" />
|
1035 |
+
<xsl:variable name="theFragment_3"
|
1036 |
+
select="$theDocument_3/*" />
|
1037 |
+
|
1038 |
+
<xsl:if test="not($theDocument_3)">
|
1039 |
+
<xsl:message terminate="no">
|
1040 |
+
<xsl:text>Unable to open referenced included file: </xsl:text>
|
1041 |
+
<xsl:value-of select="@href" />
|
1042 |
+
</xsl:message>
|
1043 |
+
</xsl:if>
|
1044 |
+
|
1045 |
+
<xsl:apply-templates select="$theFragment_3 "
|
1046 |
+
mode="dsdl:go" />
|
1047 |
+
</xsl:otherwise>
|
1048 |
+
</xsl:choose>
|
1049 |
+
|
1050 |
+
</xsl:otherwise>
|
1051 |
+
</xsl:choose>
|
1052 |
+
<xsl:processing-instruction name="DSDL_INCLUDE_END">
|
1053 |
+
<xsl:value-of select="@href" />
|
1054 |
+
</xsl:processing-instruction>
|
1055 |
+
</xslt:template>
|
1056 |
+
|
1057 |
+
<!-- =========================================================== -->
|
1058 |
+
<!-- W3C XLink 1.1 embedded simple links -->
|
1059 |
+
<!-- =========================================================== -->
|
1060 |
+
<xslt:template
|
1061 |
+
match="*[@xlink:href][not(parent::*[@xlink:type='complex'])]
|
1062 |
+
[not(@xlink:type) or (@xlink:type='simple')]
|
1063 |
+
[@xlink:show='embed']
|
1064 |
+
[not(@xlink:actuate) or (@xlink:actuate='onLoad')]"
|
1065 |
+
mode="dsdl:go" priority="1">
|
1066 |
+
|
1067 |
+
<xsl:variable name="document-uri"
|
1068 |
+
select="substring-before(concat(@xlink:href,'#'), '#')" />
|
1069 |
+
<xsl:variable name="fragment-id"
|
1070 |
+
select="substring-after(@xlink:href, '#')" />
|
1071 |
+
<xsl:processing-instruction name="DSDL_INCLUDE_START">
|
1072 |
+
<xsl:value-of select="@xlink:href" />
|
1073 |
+
</xsl:processing-instruction>
|
1074 |
+
<xsl:choose>
|
1075 |
+
<xsl:when test="not( $include-xlink = 'true' )">
|
1076 |
+
<xslt:copy>
|
1077 |
+
<xslt:copy-of select="@*" />
|
1078 |
+
<xslt:apply-templates mode="dsdl:go" />
|
1079 |
+
</xslt:copy>
|
1080 |
+
</xsl:when>
|
1081 |
+
<xsl:otherwise>
|
1082 |
+
<xsl:choose>
|
1083 |
+
|
1084 |
+
<xsl:when
|
1085 |
+
test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0">
|
1086 |
+
<xsl:message>
|
1087 |
+
Error: Impossible URL in XLink embedding
|
1088 |
+
link
|
1089 |
+
</xsl:message>
|
1090 |
+
</xsl:when>
|
1091 |
+
|
1092 |
+
<!-- this case is when there is in embedded schema in the same document elsewhere -->
|
1093 |
+
<xslt:when
|
1094 |
+
test="string-length( $document-uri ) = 0">
|
1095 |
+
<xslt:apply-templates mode="dsdl:go"
|
1096 |
+
select="//*[@xml:id= $fragment-id ] | id( $fragment-id)
|
1097 |
+
| //*[@id= $fragment-id ]" />
|
1098 |
+
</xslt:when>
|
1099 |
+
|
1100 |
+
<xsl:when
|
1101 |
+
test="string-length( $fragment-id ) > 0">
|
1102 |
+
<xsl:variable name="theDocument_1"
|
1103 |
+
select="document( $document-uri,/ )" />
|
1104 |
+
<xsl:if test="not($theDocument_1)">
|
1105 |
+
<xsl:message terminate="no">
|
1106 |
+
<xsl:text>Unable to open referenced included file: </xsl:text>
|
1107 |
+
<xsl:value-of select="@xlink:href" />
|
1108 |
+
</xsl:message>
|
1109 |
+
</xsl:if>
|
1110 |
+
<!-- use for-each to rebase id() to $theDocument -->
|
1111 |
+
<xsl:for-each select="$theDocument_1">
|
1112 |
+
<xsl:variable name="theFragment_1"
|
1113 |
+
select="$theDocument_1//*[@xml:id= $fragment-id ]
|
1114 |
+
| id( $fragment-id )
|
1115 |
+
| $theDocument_1//*[@id= $fragment-id ]" />
|
1116 |
+
<xsl:if test="not($theFragment_1)">
|
1117 |
+
<xsl:message terminate="no">
|
1118 |
+
<xsl:text>Unable to locate id attribute: </xsl:text>
|
1119 |
+
<xsl:value-of select="@xlink:href" />
|
1120 |
+
</xsl:message>
|
1121 |
+
</xsl:if>
|
1122 |
+
<xsl:apply-templates
|
1123 |
+
select=" $theFragment_1[1]" mode="dsdl:go" />
|
1124 |
+
</xsl:for-each>
|
1125 |
+
</xsl:when>
|
1126 |
+
|
1127 |
+
<xsl:otherwise>
|
1128 |
+
<xsl:variable name="theDocument_2"
|
1129 |
+
select="document( $document-uri,/ )" />
|
1130 |
+
<xsl:variable name="theFragment_2"
|
1131 |
+
select="$theDocument_2/*" />
|
1132 |
+
|
1133 |
+
<xsl:if test="not($theDocument_2)">
|
1134 |
+
<xsl:message terminate="no">
|
1135 |
+
<xsl:text>Unable to open referenced included file: </xsl:text>
|
1136 |
+
<xsl:value-of select="@xlink:href" />
|
1137 |
+
</xsl:message>
|
1138 |
+
</xsl:if>
|
1139 |
+
|
1140 |
+
<xsl:if test="not($theFragment_2)">
|
1141 |
+
<xsl:message terminate="no">
|
1142 |
+
<xsl:text>Unable to locate id attribute: </xsl:text>
|
1143 |
+
<xsl:value-of select="@xlink:href" />
|
1144 |
+
</xsl:message>
|
1145 |
+
</xsl:if>
|
1146 |
+
<xsl:apply-templates select="$theFragment_2 "
|
1147 |
+
mode="dsdl:go" />
|
1148 |
+
</xsl:otherwise>
|
1149 |
+
</xsl:choose>
|
1150 |
+
|
1151 |
+
</xsl:otherwise>
|
1152 |
+
</xsl:choose>
|
1153 |
+
|
1154 |
+
<xsl:processing-instruction name="DSDL_INCLUDE_END">
|
1155 |
+
<xsl:value-of select="@xlink:href" />
|
1156 |
+
</xsl:processing-instruction>
|
1157 |
+
</xslt:template>
|
1158 |
+
|
1159 |
+
|
1160 |
+
</xslt:stylesheet>
|
llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_message.xsl
ADDED
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<?xml version="1.0" ?><?xar XSLT?>
|
2 |
+
<!-- Implmentation for the Schematron XML Schema Language.
|
3 |
+
http://www.ascc.net/xml/resource/schematron/schematron.html
|
4 |
+
|
5 |
+
Copyright (c) 2000,2001 Rick Jelliffe and Academia Sinica Computing Center, Taiwan
|
6 |
+
|
7 |
+
This software is provided 'as-is', without any express or implied warranty.
|
8 |
+
In no event will the authors be held liable for any damages arising from
|
9 |
+
the use of this software.
|
10 |
+
|
11 |
+
Permission is granted to anyone to use this software for any purpose,
|
12 |
+
including commercial applications, and to alter it and redistribute it freely,
|
13 |
+
subject to the following restrictions:
|
14 |
+
|
15 |
+
1. The origin of this software must not be misrepresented; you must not claim
|
16 |
+
that you wrote the original software. If you use this software in a product,
|
17 |
+
an acknowledgment in the product documentation would be appreciated but is
|
18 |
+
not required.
|
19 |
+
|
20 |
+
2. Altered source versions must be plainly marked as such, and must not be
|
21 |
+
misrepresented as being the original software.
|
22 |
+
|
23 |
+
3. This notice may not be removed or altered from any source distribution.
|
24 |
+
-->
|
25 |
+
|
26 |
+
<!-- Schematron message -->
|
27 |
+
|
28 |
+
<xsl:stylesheet
|
29 |
+
version="1.0"
|
30 |
+
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
|
31 |
+
xmlns:axsl="http://www.w3.org/1999/XSL/TransformAlias">
|
32 |
+
|
33 |
+
<xsl:import href="iso_schematron_skeleton_for_xslt1.xsl"/>
|
34 |
+
|
35 |
+
<xsl:template name="process-prolog">
|
36 |
+
<axsl:output method="text" />
|
37 |
+
</xsl:template>
|
38 |
+
|
39 |
+
<!-- use default rule for process-root: copy contens / ignore title -->
|
40 |
+
<!-- use default rule for process-pattern: ignore name and see -->
|
41 |
+
<!-- use default rule for process-name: output name -->
|
42 |
+
<!-- use default rule for process-assert and process-report:
|
43 |
+
call process-message -->
|
44 |
+
|
45 |
+
<xsl:template name="process-message">
|
46 |
+
<xsl:param name="pattern" />
|
47 |
+
<xsl:param name="role" />
|
48 |
+
<axsl:message>
|
49 |
+
<xsl:apply-templates mode="text"
|
50 |
+
/> (<xsl:value-of select="$pattern" />
|
51 |
+
<xsl:if test="$role"> / <xsl:value-of select="$role" />
|
52 |
+
</xsl:if>)</axsl:message>
|
53 |
+
</xsl:template>
|
54 |
+
|
55 |
+
</xsl:stylesheet>
|
llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_skeleton_for_xslt1.xsl
ADDED
@@ -0,0 +1,1796 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<?xml version="1.0"?><?xar XSLT?>
|
2 |
+
|
3 |
+
<!--
|
4 |
+
OVERVIEW
|
5 |
+
|
6 |
+
ASCC/Schematron.com Skeleton Module for ISO Schematron (for XSLT1 systems)
|
7 |
+
|
8 |
+
ISO Schematron is a language for making assertion about the presence or absence
|
9 |
+
of patterns in XML documents. It is typically used for as a schema language, or
|
10 |
+
to augment existing schema languages, and to check business rules. It is very
|
11 |
+
powerful, yet quite simple: a developer only need know XPath and about five other
|
12 |
+
elements.
|
13 |
+
|
14 |
+
This is an open source implementation of ISO Schematron in XSLT. Although ISO does
|
15 |
+
not allow reference implementations which might compete with the text of the
|
16 |
+
standard, this code has been compiled by Rick Jelliffe, inventor of Schematron
|
17 |
+
and editor of the ISO standard; so developers can certainly use it as an
|
18 |
+
unofficial reference implementation for clarification.
|
19 |
+
|
20 |
+
This implementation is based on one by Oliver Becker. API documentation is
|
21 |
+
available separately; try www.schematron.com for this. Funding for this
|
22 |
+
stylesheet over the years has come from Topologi Pty. Ltd., Geotempo Ltd.,
|
23 |
+
and ASCC, Tapei.
|
24 |
+
|
25 |
+
There are two versions of this skeleton: one is tailored for XSLT1 processors
|
26 |
+
and the other is tailored for XSLT2 processors. Future versions of the
|
27 |
+
XSLT2 skeleton may support more features than that the XSLT 1 skeleton.
|
28 |
+
-->
|
29 |
+
<!--
|
30 |
+
TIPS
|
31 |
+
|
32 |
+
A tip for new users of Schematron: make your assertions contain positive messages
|
33 |
+
about what is expected, rather than error messages. For example, use the form
|
34 |
+
"An X should have a Y, because Z".
|
35 |
+
|
36 |
+
Another tip is that Schematron provides an
|
37 |
+
element <sch:ns> for declaring the namespaces and prefixes used in Xpaths in
|
38 |
+
attribute values; it does not extend the XML Namespaces mechanism: if a name
|
39 |
+
in an XPath has a prefix, there must be an <sch:ns> element for that prefix; if
|
40 |
+
a name in an XPath does not have a prefix, it is always in no namespace.
|
41 |
+
|
42 |
+
A tip for implementers of Schematron, either using this API or re-implementing it:
|
43 |
+
make the value of the diagnostics, flags and richer features available if possible;
|
44 |
+
Schematron has many of the optional richer features which, if implemented, provide
|
45 |
+
a compelling alternative approach to validation and business-rules checking compared
|
46 |
+
to other schema languages and programs.
|
47 |
+
|
48 |
+
If you create your own meta-stylesheet to override this one, it is a
|
49 |
+
good idea to have both in the same directory and to run the stylesheet
|
50 |
+
from that directory, as many XSLT implementations have ideosyncratic
|
51 |
+
handling of URLs: keep it simple.
|
52 |
+
-->
|
53 |
+
|
54 |
+
|
55 |
+
<!--
|
56 |
+
INVOCATION INFORMATION
|
57 |
+
|
58 |
+
The following parameters are available
|
59 |
+
|
60 |
+
phase NMTOKEN | "#ALL" (default) Select the phase for validation
|
61 |
+
allow-foreign "true" | "false" (default) Pass non-Schematron elements to the generated stylesheet
|
62 |
+
sch.exslt.imports semi-colon delimited string of filenames for some EXSLT implementations
|
63 |
+
message-newline "true" (default) | "false" Generate an extra newline at the end of messages
|
64 |
+
optimize "visit-no-attributes"
|
65 |
+
debug "true" | "false" (default) Debug mode lets compilation continue despite problems
|
66 |
+
attributes "true" | "false" (Autodetecting) Use only when the schema has no attributes as the context nodes
|
67 |
+
only-child-elements "true" | "false" (Autodetecting) Use only when the schema has no comments
|
68 |
+
or PI as the context nodes
|
69 |
+
|
70 |
+
The following parameters can be specified as Schematron variables in diagnostics, assertions and so on.
|
71 |
+
fileNameParameter string
|
72 |
+
fileDirParameter string
|
73 |
+
archiveNameParameter string In case of ZIP files
|
74 |
+
archiveDirParameter string In case of ZIP files
|
75 |
+
output-encoding Use when outputting to XML
|
76 |
+
|
77 |
+
Experimental: USE AT YOUR OWN RISK
|
78 |
+
visit-text "true" "false" Also visist text nodes for context. WARNING: NON_STARDARD.
|
79 |
+
select-contents '' | 'key' | '//' Select different implementation strategies
|
80 |
+
|
81 |
+
Conventions: Meta-stylesheets that override this may use the following parameters
|
82 |
+
generate-paths=true|false generate the @location attribute with XPaths
|
83 |
+
diagnose= yes | no Add the diagnostics to the assertion test in reports
|
84 |
+
terminate= yes | no Terminate on the first failed assertion or successful report
|
85 |
+
-->
|
86 |
+
|
87 |
+
<!--
|
88 |
+
XSLT VERSION SUPPORT
|
89 |
+
|
90 |
+
XSLT 1:
|
91 |
+
A schema using the standard XSLT 1 query binding will have a /schema/@queryBinding='xslt' or
|
92 |
+
nothing.
|
93 |
+
|
94 |
+
* Note: XT does not implement key() and will die if given it.
|
95 |
+
* Add all formal parameters to default templates
|
96 |
+
* Fix missing apply-templates from process-ns and add params back
|
97 |
+
|
98 |
+
EXSLT: Experimental support
|
99 |
+
A schema using the EXSLT query binding will have a /schema/@queryBinding='exslt'.
|
100 |
+
It is built on XSLT 1. After experience is gained, this binding is expected to be
|
101 |
+
formalized as part of ISO Schematron, which currently reserves the "exslt" name for this purpose.
|
102 |
+
|
103 |
+
Some EXSLT engines have the extra functions built-in. For these, there is no need to
|
104 |
+
provide library locations. For engines that require the functions, either hard code
|
105 |
+
them in this script or provide them on the command-line argument.
|
106 |
+
|
107 |
+
-->
|
108 |
+
<!--
|
109 |
+
PROCESS INFORMATION
|
110 |
+
|
111 |
+
This stylesheet compiles a Schematron schema (*.sch) into XSLT code (*.xsl).
|
112 |
+
The generated XSLT code can then be run against an XML file (*.xml, etc) and
|
113 |
+
will produce validation results.
|
114 |
+
|
115 |
+
The output of validation results is performed using named templates (process-*).
|
116 |
+
These can be overridden easily by making a new XSLT stylesheet that imports this
|
117 |
+
stylesheet but has its own version of the relevant process-* templates. Several
|
118 |
+
of these invoking stylesheets are available: "iso_svrl.xsl", for example generates
|
119 |
+
ISO Schematron Validation Report Language format results.
|
120 |
+
|
121 |
+
In this version of the stylesheet, the ISO feature called "abstract patterns" is
|
122 |
+
implemented using macro processing: a prior XSLT stage to which converts uses
|
123 |
+
of abstract patterns into normal patterns. If you do not use abstract patterns,
|
124 |
+
it is not necessary to preprocess the schema.
|
125 |
+
|
126 |
+
To summarize, a basic process flow for some commandline processor is like this:
|
127 |
+
XSLT -input=xxx.sch -output=xxx.xsl -stylesheet=iso_schematron_skeleton.xsl
|
128 |
+
XSLT -input=document.xml -output=xxx-document.results -stylesheet=xxx.xsl
|
129 |
+
|
130 |
+
iso_svrl.xslt is an implementation of Schematron that can use this skeleton and
|
131 |
+
generate ISO SVRL reports. A process flow for some commandline processor would
|
132 |
+
be like this:
|
133 |
+
XSLT -input=xxx.sch -output=xxx.xsl -stylesheet=iso_svrl.xsl
|
134 |
+
XSLT -input=document.xml -output=xxx-document.results -stylesheet=xxx.xsl
|
135 |
+
|
136 |
+
It is not impossible that ultimately a third stage, to handle macro-preprocessing
|
137 |
+
and inclusion, might be necessary. (The trade-off is in making this XSLT more
|
138 |
+
complex compared to making the outer process more complex.)
|
139 |
+
|
140 |
+
This version has so far been tested with
|
141 |
+
Saxon 8
|
142 |
+
MSXML 4 (or 6?)
|
143 |
+
|
144 |
+
Please note that if you are using SAXON and JAXP, then you should use
|
145 |
+
System.setProperty("javax.xml.transform.TransformerFactory",
|
146 |
+
"net.sf.saxon.TransformerFactoryImpl");
|
147 |
+
rather than
|
148 |
+
System.setProperty("javax.xml.xpath.TransformerFactory",
|
149 |
+
"net.sf.saxon.TransformerFactoryImpl");
|
150 |
+
which is does not work, at least for the versions of SAXON we tried.
|
151 |
+
-->
|
152 |
+
<!--
|
153 |
+
LEGAL INFORMATION
|
154 |
+
|
155 |
+
Copyright (c) 2000-2008 Rick Jelliffe and Academia Sinica Computing Center, Taiwan
|
156 |
+
|
157 |
+
This software is provided 'as-is', without any express or implied warranty.
|
158 |
+
In no event will the authors be held liable for any damages arising from
|
159 |
+
the use of this software.
|
160 |
+
|
161 |
+
Permission is granted to anyone to use this software for any purpose,
|
162 |
+
including commercial applications, and to alter it and redistribute it freely,
|
163 |
+
subject to the following restrictions:
|
164 |
+
|
165 |
+
1. The origin of this software must not be misrepresented; you must not claim
|
166 |
+
that you wrote the original software. If you use this software in a product,
|
167 |
+
an acknowledgment in the product documentation would be appreciated but is
|
168 |
+
not required.
|
169 |
+
|
170 |
+
2. Altered source versions must be plainly marked as such, and must not be
|
171 |
+
misrepresented as being the original software.
|
172 |
+
|
173 |
+
3. This notice may not be removed or altered from any source distribution.
|
174 |
+
-->
|
175 |
+
<!--
|
176 |
+
NOTE: Compared to the iso_schematron_skeleton_for_saxon.xsl code, this version is currently missing
|
177 |
+
1) localization
|
178 |
+
2) properties
|
179 |
+
3) pattern/@documents
|
180 |
+
|
181 |
+
VERSION INFORMATION
|
182 |
+
2009-02-25 RJ
|
183 |
+
* Fix up variable names so none are used twice in same template
|
184 |
+
* Tested on SAXON 9, Xalan 2.7.1. Partly tested MSXML.
|
185 |
+
2008-09-19 RJ
|
186 |
+
* Add mode schematron-select-full-path and param full-path-notation
|
187 |
+
|
188 |
+
2008-08-11
|
189 |
+
* TT report/@flag was missing
|
190 |
+
2008-08-06
|
191 |
+
* TT Top-level lets need to be implemented using xsl:param not xsl:variable
|
192 |
+
* TT xsl:param/@select must have XPath or not be specified
|
193 |
+
|
194 |
+
Version: 2008-07-28
|
195 |
+
* KH schematron-get-full-path-3 has [index] even on top step
|
196 |
+
* RJ fix schematron-get-full-path to have namespace predicate, I don't know why this was removed
|
197 |
+
|
198 |
+
Version: 2008-07-24
|
199 |
+
* RJ clean out commented out namespace handling code
|
200 |
+
* RJ add support for experimental non-standard attribute report/@action
|
201 |
+
and assert/@action, and add parameter not in the published API (should
|
202 |
+
not break anything, it is XSLT1)
|
203 |
+
* RJ Remove remaining XSLT2 code for ease of reading
|
204 |
+
|
205 |
+
Version: 2008-07-14 minor update for inclusion experiments
|
206 |
+
* RJ Clean up zero-length fragment test on include
|
207 |
+
* RJ Add experimental support for include containers
|
208 |
+
* RJ For path generation, test for //iso:schema not just /iso:schema, for potential embedded Schematron support
|
209 |
+
* RJ Don't generate double error messages for old namespace elements
|
210 |
+
* RJ Experimental iso:rule/iso:title just kept as comment (bigger request Uche Ogbuji)
|
211 |
+
* RJ Remove spurious debug messages
|
212 |
+
* RJ Fix bug that prevented including patterns in this (report Roger
|
213 |
+
Costello)
|
214 |
+
|
215 |
+
Version: 2007-10-17
|
216 |
+
From this version on I am forking XSLT2 support to a different version of the script.
|
217 |
+
This is due to the increasingly horrible state of the namespace handling code as well
|
218 |
+
as other inconsistencies between the major implementations of different versions.
|
219 |
+
The intent is that future versions of this will have XSLT2 isms removed and be simplified
|
220 |
+
to cope with only XSLT1 and EXLST. Note that though this version is called
|
221 |
+
iso_schematron_skeleton_for_xslt1, the various meta-stylesheets will continue to just call
|
222 |
+
iso_schematron_skeleton: it is up to you to rename the stylesheet to the one you want to
|
223 |
+
use.
|
224 |
+
|
225 |
+
* RJ fix FULL-PATH problem with attribute names
|
226 |
+
|
227 |
+
|
228 |
+
Version: 2007-07-19
|
229 |
+
Accept most changes in David Carlisle's fork, but continue as XSLT1 script:
|
230 |
+
http://dpcarlisle.blogspot.com/search/label/schematron
|
231 |
+
* DPC Remove "optimize" parameter
|
232 |
+
* DPC Add autodetecting optimize parameter attribute to skip checking attribute
|
233 |
+
context
|
234 |
+
* DPC Add autodetecting optimize parameter only-child-elements turn off checking for
|
235 |
+
comments and PIs
|
236 |
+
* DPC (Experimental: NON_STANDARD DANGER!) Add param visit-text to viist text
|
237 |
+
nodes too for context
|
238 |
+
* DPC Fix inclusion syntax to allow #
|
239 |
+
* DPC Priorities count up from 1000 not down from 4000 to allow more rules
|
240 |
+
* RJ Add new template for titles of schemas, with existing behaviour.
|
241 |
+
Override process-schema-title for custom processing of title
|
242 |
+
|
243 |
+
|
244 |
+
Version: 2007-04-04
|
245 |
+
* RJ debug mode param
|
246 |
+
* RJ alter mixed test to only test mixed branches, so the same document
|
247 |
+
could have old and new namespaces schemas in it, but each schema must
|
248 |
+
be distinct, just so as not to overconstrain things.
|
249 |
+
* KH zero-length include/@href is fatal error, but allow debug mode
|
250 |
+
* SB add hint on SAXON and JAXP
|
251 |
+
* DC generate-full-path-1 generates XLST1 code by default
|
252 |
+
Version: 2007-03-05
|
253 |
+
* AS Typo for EXSLT randome, improve comment
|
254 |
+
* KH get-schematron-full-path-2 needs to apply to attributes too
|
255 |
+
* DP document policy on extensions better
|
256 |
+
* DC use copy-of not copy for foreign elements
|
257 |
+
* DC add generate-path-2
|
258 |
+
* DC don't try to apply templates to attribute axis on attribute nodes, to
|
259 |
+
stop SAXON warning.
|
260 |
+
* RJ improve reporting of typos
|
261 |
+
|
262 |
+
Version: 2007-02-08
|
263 |
+
* KH Schematron fullpath implementation: @* handled twice and / missing
|
264 |
+
* KH Change stylesheetbody from named template to mode to allow implementers more flexibility.
|
265 |
+
Move process-ns to outside the stylesheet body.
|
266 |
+
* DP, FG, fix handling of xslt:key
|
267 |
+
* FG no iso:title/@class
|
268 |
+
* Experimental optimization 'visit-no-attributes'
|
269 |
+
* KH Experimental added schematron-get-full-path-2 which gives prefixed version for humans
|
270 |
+
* DC Move stylesheet/@version generation to after namespace handling
|
271 |
+
* DC, FG EXSLT namespace handling code
|
272 |
+
* FG add ref and commented code from FG's page on namespaces
|
273 |
+
* Start adding normalize-space() to parameter code
|
274 |
+
* Add a space between diagnostics
|
275 |
+
|
276 |
+
Version: 2007-01-22
|
277 |
+
* DP change = ($start) to = $start and =($phase) to =$phase
|
278 |
+
to run under Saxon 8.8j
|
279 |
+
* FG better title section using ( @id | sch:title)[last()]
|
280 |
+
* Default query language binding is "xslt" not "xslt1"
|
281 |
+
|
282 |
+
Version: 2007-01-19
|
283 |
+
* Simplify message newline code
|
284 |
+
* Remove termination and xpath appending to message options:
|
285 |
+
factor out as iso_schematron_terminator.xsl
|
286 |
+
* Comment out XSLT2 namespace fix temporarily
|
287 |
+
|
288 |
+
Version: 2007-01-18 (First beta candidate for comment)
|
289 |
+
* DC remove xml:space="preserve"
|
290 |
+
* FG improve comment on import statement
|
291 |
+
* DC improve comments on invocation section
|
292 |
+
* Add exploratory support for sch:schema[@queryBinding='xpath']
|
293 |
+
by allowing it and warning as lets are found
|
294 |
+
* Be strict about queryBinding spelling errors
|
295 |
+
* Extra comments on the different queryBindings
|
296 |
+
* KH Add option "message-paths" to generate XPath from output
|
297 |
+
* KH Add option "terminate" to halt with an error after the first assertion
|
298 |
+
* KH refactor paths in schematron-full-path
|
299 |
+
* Improve (?) namespace handling: no dummy attributes for prefix "xsl" generated
|
300 |
+
|
301 |
+
Version: 2007-01-15
|
302 |
+
* FG fix for calling templates
|
303 |
+
* Add formal parameters to default templates: may help XSLT 2
|
304 |
+
* Fix get-schematron-full-path
|
305 |
+
* Include skeleton1-6 is commented out by default
|
306 |
+
|
307 |
+
Version:2007-01-12 (Pre-beta release to Schematron-love-in maillist)
|
308 |
+
* Add many extra parameters to the process-* calls, so that almost
|
309 |
+
all the information in the schema can be provided to client programs.
|
310 |
+
Also, rearrange the parameters to fit in with the ISO schema, which
|
311 |
+
has "rich" and "linkable" attribute groups.
|
312 |
+
* Warn on diagnostics with no ID once only
|
313 |
+
* Improved path reporting, to handle for namespaces
|
314 |
+
* Add process-title dummy template for API
|
315 |
+
* Add command-line parameter allow-foreign (true|false) to suppress
|
316 |
+
warnings one foreign elements and pass them through to the generated
|
317 |
+
stylesheet
|
318 |
+
* remove legacy templates for the old ASCC namespace and no namespace,
|
319 |
+
and use an import statement instead. Much cleaner now!
|
320 |
+
* patterns use @id not @name
|
321 |
+
* titles can contain sub-elements
|
322 |
+
* start change sch:rule to allow attributes, PIs and comments
|
323 |
+
* the default process-* for inline elements add a leading and trailing
|
324 |
+
space, to reduce the chance of concatenation.
|
325 |
+
* add comments to make the generated code clearer
|
326 |
+
|
327 |
+
Version:2006-11-07 (ISO: first release private to schematron-love-in maillist for review)
|
328 |
+
* Duplicate pattern templates, for handling ISO namespace
|
329 |
+
* Add priority onto default and paragraph templates
|
330 |
+
* Add namespace checks
|
331 |
+
* Handle key in xsl namespace not iso
|
332 |
+
* Add include
|
333 |
+
* Improve namespace handling
|
334 |
+
* Preliminary XSLT2 and EXSLT support
|
335 |
+
* Refactor iso:schema for clarity
|
336 |
+
|
337 |
+
Version: 2003-05-26
|
338 |
+
* Fix bug with key
|
339 |
+
Version: 2003-04-16
|
340 |
+
* handle 1.6 let expressions
|
341 |
+
* make key use XSLT names, and allow anywhere
|
342 |
+
Version: 2001-06-13
|
343 |
+
* same skeleton now supports namespace or no namespace
|
344 |
+
* parameters to handlers updated for all 1.5 attributes
|
345 |
+
* diagnostic hints supported: command-line option diagnose=yes|no
|
346 |
+
* phases supported: command-line option phase=#ALL|...
|
347 |
+
* abstract rules
|
348 |
+
* compile-time error messages
|
349 |
+
* add utility routine generate-id-from-path
|
350 |
+
|
351 |
+
Contributors: Rick Jelliffe (original), Oliver Becker (architecture, XSLT2),
|
352 |
+
Miloslav Nic (diagnostic, phase, options), Ludwig Svenonius (abstract)
|
353 |
+
Uche Ogbuji (misc. bug fixes), Jim Ancona (SAXON workaround),
|
354 |
+
Francis Norton (generate-id-from-path), Robert Leftwich, Bryan Rasmussen,
|
355 |
+
Dave Pawson (include, fallback), Florent Georges (namespaces, exslt, attribute
|
356 |
+
context), Benoit Maisonny (attribute context), John Dumps (process-message newline),
|
357 |
+
Cliff Stanford (diagnostics and other newlines)
|
358 |
+
|
359 |
+
|
360 |
+
KNOWN TYPICAL LIMITATIONS:
|
361 |
+
* Don't use <sch:ns prefix="xsl" .../> with a namespace other than the standard
|
362 |
+
XSLT one. This would be a bizarre thing to do anyway.
|
363 |
+
* Don't use other prefixes for the XSLT namespace either; some implementations will
|
364 |
+
not handle it correctly.
|
365 |
+
|
366 |
+
EXTENSIONS:
|
367 |
+
ISO Schematron is designed as a framework with some standard query language
|
368 |
+
bindings. If you need to support other features, please do so safely by making
|
369 |
+
up your own @queryLanguage name: this makes it clear that your schema requires
|
370 |
+
special features. For example, default ISO Schematron does not support user
|
371 |
+
defined functions; so if you want to use the user defined function feature
|
372 |
+
in XSLT, you need to have a schema with some queryBinding attribute name like
|
373 |
+
"XSLT-with-my-functions" or whatever.
|
374 |
+
-->
|
375 |
+
|
376 |
+
|
377 |
+
|
378 |
+
|
379 |
+
<xsl:stylesheet version="1.0"
|
380 |
+
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
|
381 |
+
xmlns:axsl="http://www.w3.org/1999/XSL/TransformAlias"
|
382 |
+
xmlns:sch="http://www.ascc.net/xml/schematron"
|
383 |
+
xmlns:iso="http://purl.oclc.org/dsdl/schematron"
|
384 |
+
xmlns:exsl="http://exslt.org/common"
|
385 |
+
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
|
386 |
+
extension-element-prefixes="exsl msxsl"
|
387 |
+
>
|
388 |
+
<!-- This program implements ISO Schematron, except for abstract patterns which require a preprocess. -->
|
389 |
+
|
390 |
+
|
391 |
+
<xsl:namespace-alias stylesheet-prefix="axsl" result-prefix="xsl"/>
|
392 |
+
|
393 |
+
|
394 |
+
<!-- Category: top-level-element -->
|
395 |
+
<xsl:output method="xml" omit-xml-declaration="no" standalone="yes" indent="yes"/>
|
396 |
+
|
397 |
+
|
398 |
+
<xsl:param name="phase">
|
399 |
+
<xsl:choose>
|
400 |
+
<xsl:when test="//sch:schema/@defaultPhase">
|
401 |
+
<xsl:value-of select="//sch:schema/@defaultPhase"/>
|
402 |
+
</xsl:when>
|
403 |
+
<xsl:when test="//iso:schema/@defaultPhase">
|
404 |
+
<xsl:value-of select="//iso:schema/@defaultPhase"/>
|
405 |
+
</xsl:when>
|
406 |
+
<xsl:otherwise>#ALL</xsl:otherwise>
|
407 |
+
</xsl:choose>
|
408 |
+
</xsl:param>
|
409 |
+
|
410 |
+
<xsl:param name="allow-foreign">false</xsl:param>
|
411 |
+
|
412 |
+
<xsl:param name="message-newline">true</xsl:param>
|
413 |
+
|
414 |
+
<!-- DPC set to true if contexts should be checked on attribute nodes
|
415 |
+
defaults to true if there is any possibility that a context could match an attribute,
|
416 |
+
err on the side if caution, a context of *[.='@'] would cause this param to defualt to true
|
417 |
+
even though @ is in a string
|
418 |
+
-->
|
419 |
+
<xsl:param name="attributes">
|
420 |
+
<xsl:choose>
|
421 |
+
<xsl:when test="//iso:rule[contains(@context,'@') or contains(@context,'attribute')]">true</xsl:when>
|
422 |
+
<xsl:otherwise>false</xsl:otherwise>
|
423 |
+
</xsl:choose>
|
424 |
+
</xsl:param>
|
425 |
+
|
426 |
+
<!-- DPC set to true if contexts should be checked on just elements in the child axis
|
427 |
+
defaults to true if there is any possibility that a context could match an comment or PI
|
428 |
+
err on the side if caution, a context of *[.='('] would cause this param to defualt to true
|
429 |
+
even though ( is in a string, but node() comment() and processing-instruction() all have a (
|
430 |
+
-->
|
431 |
+
<xsl:param name="only-child-elements">
|
432 |
+
<xsl:choose>
|
433 |
+
<xsl:when test="//iso:rule[contains(@context,'(')]">true</xsl:when>
|
434 |
+
<xsl:otherwise>false</xsl:otherwise>
|
435 |
+
</xsl:choose>
|
436 |
+
</xsl:param>
|
437 |
+
|
438 |
+
<!-- DPC set to true if contexts should be checked on text nodes nodes (if only-child-elements is false)
|
439 |
+
THIS IS NON CONFORMANT BEHAVIOUR JUST FOR DISCUSSION OF A POSSIBLE CHANGE TO THE
|
440 |
+
SPECIFICATION. THIS PARAM SHOULD GO IF THE FINAL DECISION IS THAT THE SPEC DOES NOT CHANGE.
|
441 |
+
Always defaults to false
|
442 |
+
-->
|
443 |
+
<xsl:param name="visit-text" select="'false'"/>
|
444 |
+
|
445 |
+
<!-- DPC
|
446 |
+
When selecting contexts the specified behaviour is
|
447 |
+
@*|node()[not(self::text())]
|
448 |
+
The automatic settings may use
|
449 |
+
node()[not(self::text())]
|
450 |
+
@*|*
|
451 |
+
*
|
452 |
+
instead for schema for which they are equivalent.
|
453 |
+
If the params are set explictly the above may be used, and also either if
|
454 |
+
@*
|
455 |
+
@*|node()
|
456 |
+
in all cases the result may not be equivalent, for example if you specify no attributes and the schema
|
457 |
+
does have attribute contexts they will be silently ignored.
|
458 |
+
|
459 |
+
after testing it turns out that
|
460 |
+
node()[not(self::text())] is slower in saxon than *|comment()|processing-instruction()
|
461 |
+
which I find a bit surprising but anyway I'll use the longr faster version.
|
462 |
+
-->
|
463 |
+
<xsl:variable name="context-xpath">
|
464 |
+
<xsl:if test="$attributes='true'">@*|</xsl:if>
|
465 |
+
<xsl:choose>
|
466 |
+
<xsl:when test="$only-child-elements='true'">*</xsl:when>
|
467 |
+
<xsl:when test="$visit-text='true'">node()</xsl:when>
|
468 |
+
<xsl:otherwise>*|comment()|processing-instruction()</xsl:otherwise>
|
469 |
+
</xsl:choose>
|
470 |
+
</xsl:variable>
|
471 |
+
|
472 |
+
<!-- DPC if this is set to
|
473 |
+
'' use recursive templates to iterate over document tree,
|
474 |
+
'key' select all contexts with a key rather than walking the tree explictly in each mode
|
475 |
+
'//' select all contexts with // a key rather than walking the tree explictly in each mode (XSLT2 only)
|
476 |
+
-->
|
477 |
+
<xsl:param name="select-contexts" select="''"/>
|
478 |
+
|
479 |
+
|
480 |
+
<xsl:param name="output-encoding"/>
|
481 |
+
<!-- e.g. saxon file.xml file.xsl "sch.exslt.imports=.../string.xsl;.../math.xsl" -->
|
482 |
+
<xsl:param name="sch.exslt.imports"/>
|
483 |
+
|
484 |
+
<!-- Set the language code for messages -->
|
485 |
+
<xsl:param name="langCode">default</xsl:param>
|
486 |
+
|
487 |
+
<xsl:param name="debug">false</xsl:param>
|
488 |
+
|
489 |
+
|
490 |
+
<!-- Set the default for schematron-select-full-path, i.e. the notation for svrl's @location-->
|
491 |
+
<xsl:param name="full-path-notation">1</xsl:param>
|
492 |
+
|
493 |
+
<!-- Simple namespace check -->
|
494 |
+
<xsl:template match="/">
|
495 |
+
<xsl:if test="//sch:*[ancestor::iso:* or descendant::iso:*]">
|
496 |
+
<xsl:message>Schema error: Schematron elements in old and new namespaces found</xsl:message>
|
497 |
+
<xsl:if test=" $debug = 'false' " />
|
498 |
+
</xsl:if>
|
499 |
+
|
500 |
+
<xsl:apply-templates />
|
501 |
+
</xsl:template>
|
502 |
+
|
503 |
+
|
504 |
+
<!-- ============================================================== -->
|
505 |
+
<!-- ISO SCHEMATRON SCHEMA ELEMENT -->
|
506 |
+
<!-- Not handled: Abstract patterns. A pre-processor is assumed. -->
|
507 |
+
<!-- ============================================================== -->
|
508 |
+
|
509 |
+
<!-- SCHEMA -->
|
510 |
+
<!-- Default uses XSLT 1 -->
|
511 |
+
<xsl:template match="iso:schema[not(@queryBinding) or @queryBinding='xslt'
|
512 |
+
or @queryBinding='xslt1' or @queryBinding='XSLT' or @queryBinding='XSLT1'
|
513 |
+
or @queryBinding='xpath']">
|
514 |
+
<xsl:if test="
|
515 |
+
@queryBinding='xslt1' or @queryBinding='XSLT' or @queryBinding='XSLT1'">
|
516 |
+
<xsl:message>Schema error: in the queryBinding attribute, use 'xslt'</xsl:message>
|
517 |
+
</xsl:if>
|
518 |
+
<axsl:stylesheet>
|
519 |
+
<xsl:apply-templates select="iso:ns"/>
|
520 |
+
<!-- Handle the namespaces before the version attribute: reported to help SAXON -->
|
521 |
+
<xsl:attribute name="version">1.0</xsl:attribute>
|
522 |
+
|
523 |
+
<xsl:apply-templates select="." mode="stylesheetbody"/>
|
524 |
+
<!-- was xsl:call-template name="stylesheetbody"/ -->
|
525 |
+
</axsl:stylesheet>
|
526 |
+
</xsl:template>
|
527 |
+
|
528 |
+
<!-- Using EXSLT with all modeles (except function module: not applicable) -->
|
529 |
+
<xsl:template match="iso:schema[@queryBinding='exslt']" priority="10">
|
530 |
+
<xsl:comment>This XSLT was automatically generated from a Schematron schema.</xsl:comment>
|
531 |
+
<axsl:stylesheet
|
532 |
+
xmlns:date="http://exslt.org/dates-and-times"
|
533 |
+
xmlns:dyn="http://exslt.org/dynamic"
|
534 |
+
xmlns:exsl="http://exslt.org/common"
|
535 |
+
xmlns:math="http://exslt.org/math"
|
536 |
+
xmlns:random="http://exslt.org/random"
|
537 |
+
xmlns:regexp="http://exslt.org/regular-expressions"
|
538 |
+
xmlns:set="http://exslt.org/sets"
|
539 |
+
xmlns:str="http://exslt.org/strings"
|
540 |
+
extension-element-prefixes="date dyn exsl math random regexp set str" >
|
541 |
+
|
542 |
+
<xsl:apply-templates select="iso:ns"/>
|
543 |
+
<!-- Handle the namespaces before the version attribute: reported to help SAXON -->
|
544 |
+
<xsl:attribute name="version">1.0</xsl:attribute>
|
545 |
+
|
546 |
+
<xsl:apply-templates select="." mode="stylesheetbody"/>
|
547 |
+
<!-- was xsl:call-template name="stylesheetbody"/ -->
|
548 |
+
</axsl:stylesheet>
|
549 |
+
</xsl:template>
|
550 |
+
|
551 |
+
|
552 |
+
<!-- Default uses XSLT 1 -->
|
553 |
+
<xsl:template match="iso:schema" priority="-1">
|
554 |
+
<xsl:message terminate="yes" >Fail: This implementation of ISO Schematron does not work with
|
555 |
+
schemas using the "<xsl:value-of select="@queryBinding"/>" query language.</xsl:message>
|
556 |
+
</xsl:template>
|
557 |
+
|
558 |
+
<xsl:template match="*" mode="stylesheetbody">
|
559 |
+
<!--xsl:template name="stylesheetbody"-->
|
560 |
+
<xsl:comment>Implementers: please note that overriding process-prolog or process-root is
|
561 |
+
the preferred method for meta-stylesheets to use where possible. </xsl:comment><xsl:text> </xsl:text>
|
562 |
+
|
563 |
+
<!-- These parameters may contain strings with the name and directory of the file being
|
564 |
+
validated. For convenience, if the caller only has the information in a single string,
|
565 |
+
that string could be put in fileDirParameter. The archives parameters are available
|
566 |
+
for ZIP archives.
|
567 |
+
-->
|
568 |
+
|
569 |
+
<axsl:param name="archiveDirParameter" />
|
570 |
+
<axsl:param name="archiveNameParameter" />
|
571 |
+
<axsl:param name="fileNameParameter" />
|
572 |
+
<axsl:param name="fileDirParameter" />
|
573 |
+
|
574 |
+
<xsl:call-template name="iso:exslt.add.imports" />
|
575 |
+
<xsl:text> </xsl:text><xsl:comment>PHASES</xsl:comment><xsl:text> </xsl:text>
|
576 |
+
<xsl:call-template name="handle-phase"/>
|
577 |
+
<xsl:text> </xsl:text><xsl:comment>PROLOG</xsl:comment><xsl:text> </xsl:text>
|
578 |
+
<xsl:call-template name="process-prolog"/>
|
579 |
+
<xsl:text> </xsl:text><xsl:comment>KEYS</xsl:comment><xsl:text> </xsl:text>
|
580 |
+
<xsl:apply-templates mode="do-keys" select="xsl:key "/>
|
581 |
+
<xsl:text> </xsl:text><xsl:comment>DEFAULT RULES</xsl:comment><xsl:text> </xsl:text>
|
582 |
+
<xsl:call-template name="generate-default-rules" />
|
583 |
+
<xsl:text> </xsl:text><xsl:comment>SCHEMA METADATA</xsl:comment><xsl:text> </xsl:text>
|
584 |
+
<xsl:call-template name="handle-root"/>
|
585 |
+
<xsl:text> </xsl:text><xsl:comment>SCHEMATRON PATTERNS</xsl:comment><xsl:text> </xsl:text>
|
586 |
+
|
587 |
+
<xsl:apply-templates select="*[not(self::iso:ns)] " />
|
588 |
+
</xsl:template>
|
589 |
+
|
590 |
+
<xsl:template name="iso:exslt.add.imports">
|
591 |
+
<xsl:param name="imports" select="$sch.exslt.imports"/>
|
592 |
+
<xsl:choose>
|
593 |
+
<xsl:when test="contains($imports, ';')">
|
594 |
+
<axsl:import href="{ substring-before($imports, ';') }"/>
|
595 |
+
<xsl:call-template name="iso:exslt.add.imports">
|
596 |
+
<xsl:with-param name="imports" select="substring-after($imports, ';')"/>
|
597 |
+
</xsl:call-template>
|
598 |
+
</xsl:when>
|
599 |
+
<xsl:when test="$imports">
|
600 |
+
<axsl:import href="{ $imports }"/>
|
601 |
+
</xsl:when>
|
602 |
+
</xsl:choose>
|
603 |
+
</xsl:template>
|
604 |
+
|
605 |
+
<xsl:template name="handle-phase" >
|
606 |
+
<xsl:if test="not(normalize-space( $phase ) = '#ALL')">
|
607 |
+
<xsl:if test="not(iso:phase[@id = normalize-space( $phase )])">
|
608 |
+
<xsl:message>Phase Error: no phase with name <xsl:value-of select="normalize-space( $phase )"
|
609 |
+
/> has been defined.</xsl:message>
|
610 |
+
</xsl:if>
|
611 |
+
</xsl:if>
|
612 |
+
</xsl:template>
|
613 |
+
|
614 |
+
<xsl:template name="generate-default-rules">
|
615 |
+
<xsl:text> </xsl:text>
|
616 |
+
<xsl:comment>MODE: SCHEMATRON-SELECT-FULL-PATH</xsl:comment><xsl:text> </xsl:text>
|
617 |
+
<xsl:comment>This mode can be used to generate an ugly though full XPath for locators</xsl:comment><xsl:text> </xsl:text>
|
618 |
+
<axsl:template match="*" mode="schematron-select-full-path">
|
619 |
+
<xsl:choose>
|
620 |
+
<xsl:when test=" $full-path-notation = '1' ">
|
621 |
+
<!-- Use for computers, but rather unreadable for humans -->
|
622 |
+
<axsl:apply-templates select="." mode="schematron-get-full-path"/>
|
623 |
+
</xsl:when>
|
624 |
+
<xsl:when test=" $full-path-notation = '2' ">
|
625 |
+
<!-- Use for humans, but no good for paths unless namespaces are known out-of-band -->
|
626 |
+
<axsl:apply-templates select="." mode="schematron-get-full-path-2"/>
|
627 |
+
</xsl:when>
|
628 |
+
<xsl:when test=" $full-path-notation = '3' ">
|
629 |
+
<!-- Obsolescent. Use for humans, but no good for paths unless namespaces are known out-of-band -->
|
630 |
+
<axsl:apply-templates select="." mode="schematron-get-full-path-3"/>
|
631 |
+
</xsl:when>
|
632 |
+
|
633 |
+
<xsl:otherwise >
|
634 |
+
<!-- Use for computers, but rather unreadable for humans -->
|
635 |
+
<axsl:apply-templates select="." mode="schematron-get-full-path"/>
|
636 |
+
</xsl:otherwise>
|
637 |
+
</xsl:choose>
|
638 |
+
</axsl:template>
|
639 |
+
|
640 |
+
|
641 |
+
<xsl:text> </xsl:text>
|
642 |
+
<xsl:comment>MODE: SCHEMATRON-FULL-PATH</xsl:comment><xsl:text> </xsl:text>
|
643 |
+
<xsl:comment>This mode can be used to generate an ugly though full XPath for locators</xsl:comment><xsl:text> </xsl:text>
|
644 |
+
<axsl:template match="*" mode="schematron-get-full-path">
|
645 |
+
<axsl:apply-templates select="parent::*" mode="schematron-get-full-path"/>
|
646 |
+
|
647 |
+
<!-- XSLT1 syntax -->
|
648 |
+
|
649 |
+
<axsl:text>/</axsl:text>
|
650 |
+
<axsl:choose>
|
651 |
+
<axsl:when test="namespace-uri()=''">
|
652 |
+
<axsl:value-of select="name()"/>
|
653 |
+
<axsl:variable name="p_1" select="1+
|
654 |
+
count(preceding-sibling::*[name()=name(current())])" />
|
655 |
+
<axsl:if test="$p_1>1 or following-sibling::*[name()=name(current())]">
|
656 |
+
<xsl:text/>[<axsl:value-of select="$p_1"/>]<xsl:text/>
|
657 |
+
</axsl:if>
|
658 |
+
</axsl:when>
|
659 |
+
<axsl:otherwise>
|
660 |
+
<axsl:text>*[local-name()='</axsl:text>
|
661 |
+
<axsl:value-of select="local-name()"/><axsl:text>' and namespace-uri()='</axsl:text>
|
662 |
+
<axsl:value-of select="namespace-uri()"/>
|
663 |
+
<axsl:text>']</axsl:text>
|
664 |
+
<axsl:variable name="p_2" select="1+
|
665 |
+
count(preceding-sibling::*[local-name()=local-name(current())])" />
|
666 |
+
<axsl:if test="$p_2>1 or following-sibling::*[local-name()=local-name(current())]">
|
667 |
+
<xsl:text/>[<axsl:value-of select="$p_2"/>]<xsl:text/>
|
668 |
+
</axsl:if>
|
669 |
+
</axsl:otherwise>
|
670 |
+
</axsl:choose>
|
671 |
+
</axsl:template>
|
672 |
+
|
673 |
+
|
674 |
+
<axsl:template match="@*" mode="schematron-get-full-path">
|
675 |
+
|
676 |
+
<!-- XSLT1 syntax -->
|
677 |
+
<axsl:text>/</axsl:text>
|
678 |
+
<axsl:choose>
|
679 |
+
<axsl:when test="namespace-uri()=''">@<axsl:value-of
|
680 |
+
select="name()"/></axsl:when>
|
681 |
+
<axsl:otherwise>
|
682 |
+
<axsl:text>@*[local-name()='</axsl:text>
|
683 |
+
<axsl:value-of select="local-name()"/>
|
684 |
+
<axsl:text>' and namespace-uri()='</axsl:text>
|
685 |
+
<axsl:value-of select="namespace-uri()"/>
|
686 |
+
<axsl:text>']</axsl:text>
|
687 |
+
</axsl:otherwise>
|
688 |
+
</axsl:choose>
|
689 |
+
|
690 |
+
</axsl:template>
|
691 |
+
|
692 |
+
|
693 |
+
<xsl:text> </xsl:text>
|
694 |
+
|
695 |
+
<xsl:comment>MODE: SCHEMATRON-FULL-PATH-2</xsl:comment>
|
696 |
+
<xsl:text> </xsl:text>
|
697 |
+
<xsl:comment>This mode can be used to generate prefixed XPath for humans</xsl:comment>
|
698 |
+
<xsl:text> </xsl:text>
|
699 |
+
<!--simplify the error messages by using the namespace prefixes of the
|
700 |
+
instance rather than the generic namespace-uri-styled qualification-->
|
701 |
+
<axsl:template match="node() | @*" mode="schematron-get-full-path-2">
|
702 |
+
<!--report the element hierarchy-->
|
703 |
+
<axsl:for-each select="ancestor-or-self::*">
|
704 |
+
<axsl:text>/</axsl:text>
|
705 |
+
<axsl:value-of select="name(.)"/>
|
706 |
+
<axsl:if test="preceding-sibling::*[name(.)=name(current())]">
|
707 |
+
<axsl:text>[</axsl:text>
|
708 |
+
<axsl:value-of
|
709 |
+
select="count(preceding-sibling::*[name(.)=name(current())])+1"/>
|
710 |
+
<axsl:text>]</axsl:text>
|
711 |
+
</axsl:if>
|
712 |
+
</axsl:for-each>
|
713 |
+
<!--report the attribute-->
|
714 |
+
<axsl:if test="not(self::*)">
|
715 |
+
<axsl:text/>/@<axsl:value-of select="name(.)"/>
|
716 |
+
</axsl:if>
|
717 |
+
</axsl:template>
|
718 |
+
|
719 |
+
<xsl:text> </xsl:text>
|
720 |
+
<xsl:comment>MODE: GENERATE-ID-FROM-PATH </xsl:comment><xsl:text> </xsl:text>
|
721 |
+
<!-- repeatable-id maker derived from Francis Norton's. -->
|
722 |
+
<!-- use this if you need generate ids in separate passes,
|
723 |
+
because generate-id() is not guaranteed to produce the same
|
724 |
+
results each time. These ids are not XML names but closer to paths. -->
|
725 |
+
<axsl:template match="/" mode="generate-id-from-path"/>
|
726 |
+
<axsl:template match="text()" mode="generate-id-from-path">
|
727 |
+
<axsl:apply-templates select="parent::*" mode="generate-id-from-path"/>
|
728 |
+
<axsl:value-of select="concat('.text-', 1+count(preceding-sibling::text()), '-')"/>
|
729 |
+
</axsl:template>
|
730 |
+
<axsl:template match="comment()" mode="generate-id-from-path">
|
731 |
+
<axsl:apply-templates select="parent::*" mode="generate-id-from-path"/>
|
732 |
+
<axsl:value-of select="concat('.comment-', 1+count(preceding-sibling::comment()), '-')"/>
|
733 |
+
</axsl:template>
|
734 |
+
<axsl:template match="processing-instruction()" mode="generate-id-from-path">
|
735 |
+
<axsl:apply-templates select="parent::*" mode="generate-id-from-path"/>
|
736 |
+
<axsl:value-of
|
737 |
+
select="concat('.processing-instruction-', 1+count(preceding-sibling::processing-instruction()), '-')"/>
|
738 |
+
</axsl:template>
|
739 |
+
<axsl:template match="@*" mode="generate-id-from-path">
|
740 |
+
<axsl:apply-templates select="parent::*" mode="generate-id-from-path"/>
|
741 |
+
<axsl:value-of select="concat('.@', name())"/>
|
742 |
+
</axsl:template>
|
743 |
+
<axsl:template match="*" mode="generate-id-from-path" priority="-0.5">
|
744 |
+
<axsl:apply-templates select="parent::*" mode="generate-id-from-path"/>
|
745 |
+
<axsl:text>.</axsl:text>
|
746 |
+
<!--
|
747 |
+
<axsl:choose>
|
748 |
+
<axsl:when test="count(. | ../namespace::*) = count(../namespace::*)">
|
749 |
+
<axsl:value-of select="concat('.namespace::-',1+count(namespace::*),'-')"/>
|
750 |
+
</axsl:when>
|
751 |
+
<axsl:otherwise>
|
752 |
+
-->
|
753 |
+
<axsl:value-of
|
754 |
+
select="concat('.',name(),'-',1+count(preceding-sibling::*[name()=name(current())]),'-')"/>
|
755 |
+
<!--
|
756 |
+
</axsl:otherwise>
|
757 |
+
</axsl:choose>
|
758 |
+
-->
|
759 |
+
</axsl:template>
|
760 |
+
|
761 |
+
|
762 |
+
<xsl:comment>MODE: SCHEMATRON-FULL-PATH-3</xsl:comment>
|
763 |
+
|
764 |
+
<xsl:text> </xsl:text>
|
765 |
+
<xsl:comment>This mode can be used to generate prefixed XPath for humans
|
766 |
+
(Top-level element has index)</xsl:comment>
|
767 |
+
<xsl:text> </xsl:text>
|
768 |
+
<!--simplify the error messages by using the namespace prefixes of the
|
769 |
+
instance rather than the generic namespace-uri-styled qualification-->
|
770 |
+
<axsl:template match="node() | @*" mode="schematron-get-full-path-3">
|
771 |
+
<!--report the element hierarchy-->
|
772 |
+
<axsl:for-each select="ancestor-or-self::*">
|
773 |
+
<axsl:text>/</axsl:text>
|
774 |
+
<axsl:value-of select="name(.)"/>
|
775 |
+
<axsl:if test="parent::*">
|
776 |
+
<axsl:text>[</axsl:text>
|
777 |
+
<axsl:value-of
|
778 |
+
select="count(preceding-sibling::*[name(.)=name(current())])+1"/>
|
779 |
+
<axsl:text>]</axsl:text>
|
780 |
+
</axsl:if>
|
781 |
+
</axsl:for-each>
|
782 |
+
<!--report the attribute-->
|
783 |
+
<axsl:if test="not(self::*)">
|
784 |
+
<axsl:text/>/@<axsl:value-of select="name(.)"/>
|
785 |
+
</axsl:if>
|
786 |
+
</axsl:template>
|
787 |
+
|
788 |
+
<xsl:text> </xsl:text>
|
789 |
+
<xsl:comment>MODE: GENERATE-ID-2 </xsl:comment><xsl:text> </xsl:text>
|
790 |
+
<!-- repeatable-id maker from David Carlisle. -->
|
791 |
+
<!-- use this if you need generate IDs in separate passes,
|
792 |
+
because generate-id() is not guaranteed to produce the same
|
793 |
+
results each time. These IDs are well-formed XML NMTOKENS -->
|
794 |
+
<axsl:template match="/" mode="generate-id-2">U</axsl:template>
|
795 |
+
|
796 |
+
<axsl:template match="*" mode="generate-id-2" priority="2">
|
797 |
+
<axsl:text>U</axsl:text>
|
798 |
+
<axsl:number level="multiple" count="*"/>
|
799 |
+
</axsl:template>
|
800 |
+
|
801 |
+
<axsl:template match="node()" mode="generate-id-2">
|
802 |
+
<axsl:text>U.</axsl:text>
|
803 |
+
<axsl:number level="multiple" count="*"/>
|
804 |
+
<axsl:text>n</axsl:text>
|
805 |
+
<axsl:number count="node()"/>
|
806 |
+
</axsl:template>
|
807 |
+
|
808 |
+
<axsl:template match="@*" mode="generate-id-2">
|
809 |
+
<axsl:text>U.</axsl:text>
|
810 |
+
<axsl:number level="multiple" count="*"/>
|
811 |
+
<axsl:text>_</axsl:text>
|
812 |
+
<axsl:value-of select="string-length(local-name(.))"/>
|
813 |
+
<axsl:text>_</axsl:text>
|
814 |
+
<axsl:value-of select="translate(name(),':','.')"/>
|
815 |
+
</axsl:template>
|
816 |
+
|
817 |
+
|
818 |
+
<xsl:comment>Strip characters</xsl:comment>
|
819 |
+
<axsl:template match="text()" priority="-1" />
|
820 |
+
|
821 |
+
</xsl:template>
|
822 |
+
|
823 |
+
<xsl:template name="handle-root">
|
824 |
+
<!-- Process the top-level element -->
|
825 |
+
<axsl:template match="/">
|
826 |
+
<xsl:call-template name="process-root">
|
827 |
+
<xsl:with-param
|
828 |
+
name="title" select="(@id | iso:title)[last()]"/>
|
829 |
+
<xsl:with-param name="version" select="'iso'" />
|
830 |
+
<xsl:with-param name="schemaVersion" select="@schemaVersion" />
|
831 |
+
<xsl:with-param name="queryBinding" select="@queryBinding" />
|
832 |
+
<xsl:with-param name="contents">
|
833 |
+
<xsl:apply-templates mode="do-all-patterns"/>
|
834 |
+
</xsl:with-param>
|
835 |
+
|
836 |
+
<!-- "Rich" properties -->
|
837 |
+
<xsl:with-param name="fpi" select="@fpi"/>
|
838 |
+
<xsl:with-param name="icon" select="@icon"/>
|
839 |
+
<xsl:with-param name="id" select="@id"/>
|
840 |
+
<xsl:with-param name="lang" select="@xml:lang"/>
|
841 |
+
<xsl:with-param name="see" select="@see" />
|
842 |
+
<xsl:with-param name="space" select="@xml:space" />
|
843 |
+
|
844 |
+
|
845 |
+
<!-- Non-standard extensions not part of the API yet -->
|
846 |
+
<xsl:with-param name="action" select="@action" />
|
847 |
+
</xsl:call-template>
|
848 |
+
</axsl:template>
|
849 |
+
|
850 |
+
|
851 |
+
</xsl:template>
|
852 |
+
|
853 |
+
<!-- ============================================================== -->
|
854 |
+
<!-- ISO SCHEMATRON ELEMENTS -->
|
855 |
+
<!-- ============================================================== -->
|
856 |
+
|
857 |
+
<!-- ISO ACTIVE -->
|
858 |
+
<xsl:template match="iso:active">
|
859 |
+
<xsl:if test="not(@pattern)">
|
860 |
+
<xsl:message>Markup Error: no pattern attribute in <active></xsl:message>
|
861 |
+
</xsl:if>
|
862 |
+
|
863 |
+
<xsl:if test="not(../../iso:pattern[@id = current()/@pattern])
|
864 |
+
and not(../../iso:include)">
|
865 |
+
<xsl:message>Reference Error: the pattern "<xsl:value-of select="@pattern"
|
866 |
+
/>" has been activated but is not declared</xsl:message>
|
867 |
+
</xsl:if>
|
868 |
+
</xsl:template>
|
869 |
+
|
870 |
+
<!-- ISO ASSERT and REPORT -->
|
871 |
+
<xsl:template match="iso:assert">
|
872 |
+
|
873 |
+
<xsl:if test="not(@test)">
|
874 |
+
<xsl:message>Markup Error: no test attribute in <assert</xsl:message>
|
875 |
+
</xsl:if>
|
876 |
+
<xsl:text> </xsl:text>
|
877 |
+
<xsl:comment>ASSERT <xsl:value-of select="@role" /> </xsl:comment><xsl:text> </xsl:text>
|
878 |
+
|
879 |
+
<axsl:choose>
|
880 |
+
<axsl:when test="{@test}"/>
|
881 |
+
<axsl:otherwise>
|
882 |
+
<xsl:call-template name="process-assert">
|
883 |
+
<xsl:with-param name="test" select="normalize-space(@test)" />
|
884 |
+
<xsl:with-param name="diagnostics" select="@diagnostics"/>
|
885 |
+
<xsl:with-param name="flag" select="@flag"/>
|
886 |
+
|
887 |
+
<!-- "Rich" properties -->
|
888 |
+
<xsl:with-param name="fpi" select="@fpi"/>
|
889 |
+
<xsl:with-param name="icon" select="@icon"/>
|
890 |
+
<xsl:with-param name="id" select="@id"/>
|
891 |
+
<xsl:with-param name="lang" select="@xml:lang"/>
|
892 |
+
<xsl:with-param name="see" select="@see" />
|
893 |
+
<xsl:with-param name="space" select="@xml:space" />
|
894 |
+
|
895 |
+
<!-- "Linking" properties -->
|
896 |
+
<xsl:with-param name="role" select="@role" />
|
897 |
+
<xsl:with-param name="subject" select="@subject" />
|
898 |
+
</xsl:call-template>
|
899 |
+
|
900 |
+
</axsl:otherwise>
|
901 |
+
</axsl:choose>
|
902 |
+
</xsl:template>
|
903 |
+
<xsl:template match="iso:report">
|
904 |
+
|
905 |
+
<xsl:if test="not(@test)">
|
906 |
+
<xsl:message>Markup Error: no test attribute in <report></xsl:message>
|
907 |
+
</xsl:if>
|
908 |
+
|
909 |
+
<xsl:text> </xsl:text>
|
910 |
+
<xsl:comment>REPORT <xsl:value-of select="@role" /> </xsl:comment><xsl:text> </xsl:text>
|
911 |
+
|
912 |
+
<axsl:if test="{@test}">
|
913 |
+
|
914 |
+
<xsl:call-template name="process-report">
|
915 |
+
<xsl:with-param name="test" select="normalize-space(@test)" />
|
916 |
+
<xsl:with-param name="diagnostics" select="@diagnostics"/>
|
917 |
+
<xsl:with-param name="flag" select="@flag"/>
|
918 |
+
|
919 |
+
<!-- "Rich" properties -->
|
920 |
+
<xsl:with-param name="fpi" select="@fpi"/>
|
921 |
+
<xsl:with-param name="icon" select="@icon"/>
|
922 |
+
<xsl:with-param name="id" select="@id"/>
|
923 |
+
<xsl:with-param name="lang" select="@xml:lang"/>
|
924 |
+
<xsl:with-param name="see" select="@see" />
|
925 |
+
<xsl:with-param name="space" select="@xml:space" />
|
926 |
+
|
927 |
+
<!-- "Linking" properties -->
|
928 |
+
<xsl:with-param name="role" select="@role" />
|
929 |
+
<xsl:with-param name="subject" select="@subject" />
|
930 |
+
</xsl:call-template>
|
931 |
+
|
932 |
+
</axsl:if>
|
933 |
+
</xsl:template>
|
934 |
+
|
935 |
+
|
936 |
+
<!-- ISO DIAGNOSTIC -->
|
937 |
+
<!-- We use a mode here to maintain backwards compatability, instead of adding it
|
938 |
+
to the other mode.
|
939 |
+
-->
|
940 |
+
<xsl:template match="iso:diagnostic" mode="check-diagnostics">
|
941 |
+
<xsl:if test="not(@id)">
|
942 |
+
<xsl:message>Markup Error: no id attribute in <diagnostic></xsl:message>
|
943 |
+
</xsl:if>
|
944 |
+
</xsl:template>
|
945 |
+
|
946 |
+
<xsl:template match="iso:diagnostic" >
|
947 |
+
<xsl:call-template name="process-diagnostic">
|
948 |
+
|
949 |
+
<!-- "Rich" properties -->
|
950 |
+
<xsl:with-param name="fpi" select="@fpi"/>
|
951 |
+
<xsl:with-param name="icon" select="@icon"/>
|
952 |
+
<xsl:with-param name="id" select="@id"/>
|
953 |
+
<xsl:with-param name="lang" select="@xml:lang"/>
|
954 |
+
<xsl:with-param name="see" select="@see" />
|
955 |
+
<xsl:with-param name="space" select="@xml:space" />
|
956 |
+
</xsl:call-template>
|
957 |
+
</xsl:template>
|
958 |
+
|
959 |
+
<!-- ISO DIAGNOSTICS -->
|
960 |
+
<xsl:template match="iso:diagnostics" >
|
961 |
+
<xsl:apply-templates mode="check-diagnostics" select="*" />
|
962 |
+
</xsl:template>
|
963 |
+
|
964 |
+
<!-- ISO DIR -->
|
965 |
+
<xsl:template match="iso:dir" mode="text" >
|
966 |
+
<xsl:call-template name="process-dir">
|
967 |
+
<xsl:with-param name="value" select="@value"/>
|
968 |
+
</xsl:call-template>
|
969 |
+
</xsl:template>
|
970 |
+
|
971 |
+
<!-- ISO EMPH -->
|
972 |
+
<xsl:template match="iso:emph" mode="text">
|
973 |
+
|
974 |
+
<xsl:call-template name="process-emph"/>
|
975 |
+
|
976 |
+
</xsl:template>
|
977 |
+
|
978 |
+
<!-- ISO EXTENDS -->
|
979 |
+
<xsl:template match="iso:extends">
|
980 |
+
<xsl:if test="not(@rule)">
|
981 |
+
<xsl:message>Markup Error: no rule attribute in <extends></xsl:message>
|
982 |
+
</xsl:if>
|
983 |
+
<xsl:if test="not(//iso:rule[@abstract='true'][@id= current()/@rule] )">
|
984 |
+
<xsl:message>Reference Error: the abstract rule "<xsl:value-of select="@rule"
|
985 |
+
/>" has been referenced but is not declared</xsl:message>
|
986 |
+
</xsl:if>
|
987 |
+
<xsl:call-template name="IamEmpty" />
|
988 |
+
|
989 |
+
<xsl:if test="//iso:rule[@id=current()/@rule]">
|
990 |
+
<xsl:apply-templates select="//iso:rule[@id=current()/@rule]"
|
991 |
+
mode="extends"/>
|
992 |
+
</xsl:if>
|
993 |
+
|
994 |
+
</xsl:template>
|
995 |
+
|
996 |
+
<!-- KEY: ISO has no KEY -->
|
997 |
+
<!-- NOTE:
|
998 |
+
Key has had a checkered history. Schematron 1.0 allowed it in certain places, but
|
999 |
+
users came up with a different location, which has now been adopted.
|
1000 |
+
|
1001 |
+
XT, the early XSLT processor, did not implement key and died when it was present.
|
1002 |
+
So there are some versions of the Schematron skeleton for XT that strip out all
|
1003 |
+
key elements.
|
1004 |
+
|
1005 |
+
Xalan (e.g. Xalan4C 1.0 and a Xalan4J) also had a funny. A fix involved making
|
1006 |
+
a top-level parameter called $hiddenKey and then using that instead of matching
|
1007 |
+
"key". This has been removed.
|
1008 |
+
-->
|
1009 |
+
<xsl:template match="xsl:key" mode="do-keys" >
|
1010 |
+
<xsl:if test="not(@name)">
|
1011 |
+
<xsl:message>Markup Error: no name attribute in <key></xsl:message>
|
1012 |
+
</xsl:if>
|
1013 |
+
<xsl:if test="not(@path) and not(@use)">
|
1014 |
+
<xsl:message>Markup Error: no path or use attribute in <key></xsl:message>
|
1015 |
+
</xsl:if>
|
1016 |
+
<xsl:choose>
|
1017 |
+
<xsl:when test="parent::iso:rule ">
|
1018 |
+
<xsl:call-template name="IamEmpty" />
|
1019 |
+
<xsl:choose>
|
1020 |
+
<xsl:when test="@path">
|
1021 |
+
<axsl:key match="{../@context}" name="{@name}" use="{@path}"/>
|
1022 |
+
</xsl:when>
|
1023 |
+
<xsl:otherwise>
|
1024 |
+
<axsl:key match="{../@context}" name="{@name}" use="{@use}"/>
|
1025 |
+
</xsl:otherwise>
|
1026 |
+
</xsl:choose>
|
1027 |
+
</xsl:when>
|
1028 |
+
<xsl:otherwise>
|
1029 |
+
<xsl:if test="not(@match) ">
|
1030 |
+
<xsl:message>Markup Error: no path or use attribute in <key></xsl:message>
|
1031 |
+
</xsl:if>
|
1032 |
+
<axsl:key>
|
1033 |
+
<xsl:copy-of select="@*"/>
|
1034 |
+
</axsl:key>
|
1035 |
+
</xsl:otherwise>
|
1036 |
+
</xsl:choose>
|
1037 |
+
</xsl:template>
|
1038 |
+
|
1039 |
+
<xsl:template match="xsl:key " /><!-- swallow -->
|
1040 |
+
|
1041 |
+
<xsl:template match="iso:key " >
|
1042 |
+
<xsl:message>Schema error: The key element is not in the ISO Schematron namespace. Use the XSLT namespace.</xsl:message>
|
1043 |
+
</xsl:template>
|
1044 |
+
|
1045 |
+
<!-- ISO INCLUDE -->
|
1046 |
+
<!-- This is only a fallback. Include really needs to have been done before this as a separate pass.-->
|
1047 |
+
|
1048 |
+
<xsl:template match="iso:include[not(normalize-space(@href))]"
|
1049 |
+
priority="1">
|
1050 |
+
<xsl:if test=" $debug = 'false' ">
|
1051 |
+
<xsl:message terminate="yes">Schema error: Empty href= attribute for include directive.</xsl:message>
|
1052 |
+
</xsl:if>
|
1053 |
+
|
1054 |
+
</xsl:template>
|
1055 |
+
|
1056 |
+
<!-- Extend the URI syntax to allow # refererences -->
|
1057 |
+
<!-- Add experimental support for simple containers like /xxx:xxx/iso:pattern to allow better includes -->
|
1058 |
+
<xsl:template match="iso:include">
|
1059 |
+
<xsl:variable name="document-uri" select="substring-before(concat(@href,'#'), '#')"/>
|
1060 |
+
<xsl:variable name="fragment-id" select="substring-after(@href, '#')"/>
|
1061 |
+
|
1062 |
+
<xsl:choose>
|
1063 |
+
|
1064 |
+
<xsl:when test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0" >
|
1065 |
+
<xsl:message>Error: Impossible URL in Schematron include</xsl:message>
|
1066 |
+
</xsl:when>
|
1067 |
+
|
1068 |
+
<xsl:when test="string-length( $fragment-id ) > 0">
|
1069 |
+
<xsl:variable name="theDocument_1" select="document( $document-uri,/ )" />
|
1070 |
+
<xsl:variable name="theFragment_1" select="$theDocument_1//iso:*[@id= $fragment-id ]" />
|
1071 |
+
<xsl:if test=" $theFragment_1/self::iso:schema ">
|
1072 |
+
<xsl:message>Schema error: Use include to include fragments, not a whole schema</xsl:message>
|
1073 |
+
</xsl:if>
|
1074 |
+
<xsl:apply-templates select=" $theFragment_1"/>
|
1075 |
+
</xsl:when>
|
1076 |
+
|
1077 |
+
<xsl:otherwise>
|
1078 |
+
<xsl:variable name="theDocument_2" select="document( $document-uri,/ )" />
|
1079 |
+
<xsl:variable name="theFragment_2" select="$theDocument_2/iso:*" />
|
1080 |
+
<xsl:variable name="theContainedFragments" select="$theDocument_2/*/iso:*" />
|
1081 |
+
<xsl:if test=" $theFragment_2/self::iso:schema or $theContainedFragments/self::iso:schema">
|
1082 |
+
<xsl:message>Schema error: Use include to include fragments, not a whole schema</xsl:message>
|
1083 |
+
</xsl:if>
|
1084 |
+
<xsl:apply-templates select="$theFragment_2 | $theContainedFragments "/>
|
1085 |
+
</xsl:otherwise>
|
1086 |
+
</xsl:choose>
|
1087 |
+
</xsl:template>
|
1088 |
+
|
1089 |
+
<!-- This is to handle the particular case of including patterns -->
|
1090 |
+
<xsl:template match="iso:include" mode="do-all-patterns">
|
1091 |
+
<xsl:variable name="document-uri" select="substring-before(concat(@href,'#'), '#')"/>
|
1092 |
+
<xsl:variable name="fragment-id" select="substring-after(@href, '#')"/>
|
1093 |
+
|
1094 |
+
<xsl:choose>
|
1095 |
+
|
1096 |
+
<xsl:when test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0" >
|
1097 |
+
<xsl:message>Error: Impossible URL in Schematron include</xsl:message>
|
1098 |
+
</xsl:when>
|
1099 |
+
|
1100 |
+
<xsl:when test="string-length( $fragment-id ) > 0">
|
1101 |
+
<xsl:variable name="theDocument_1" select="document( $document-uri,/ )" />
|
1102 |
+
<xsl:variable name="theFragment_1" select="$theDocument_1//iso:*[@id= $fragment-id ]" />
|
1103 |
+
<xsl:if test=" $theFragment_1/self::iso:schema ">
|
1104 |
+
<xsl:message>Schema error: Use include to include fragments, not a whole schema</xsl:message>
|
1105 |
+
</xsl:if>
|
1106 |
+
<xsl:apply-templates select=" $theFragment_1" mode="do-all-patterns"/>
|
1107 |
+
</xsl:when>
|
1108 |
+
|
1109 |
+
<xsl:otherwise>
|
1110 |
+
<!-- Import the top-level element if it is in schematron namespace,
|
1111 |
+
or its children otherwise, to allow a simple containment mechanism. -->
|
1112 |
+
<xsl:variable name="theDocument_2" select="document( $document-uri,/ )" />
|
1113 |
+
<xsl:variable name="theFragment_2" select="$theDocument_2/iso:*" />
|
1114 |
+
<xsl:variable name="theContainedFragments" select="$theDocument_2/*/iso:*" />
|
1115 |
+
<xsl:if test=" $theFragment_2/self::iso:schema or $theContainedFragments/self::iso:schema">
|
1116 |
+
<xsl:message>Schema error: Use include to include fragments, not a whole schema</xsl:message>
|
1117 |
+
</xsl:if>
|
1118 |
+
<xsl:apply-templates select="$theFragment_2 | $theContainedFragments "
|
1119 |
+
mode="do-all-patterns" />
|
1120 |
+
</xsl:otherwise>
|
1121 |
+
</xsl:choose>
|
1122 |
+
</xsl:template>
|
1123 |
+
|
1124 |
+
<!-- ISO LET -->
|
1125 |
+
<xsl:template match="iso:let" >
|
1126 |
+
<xsl:if test="ancestor::iso:schema[@queryBinding='xpath']">
|
1127 |
+
<xsl:message>Warning: Variables should not be used with the "xpath" query language binding.</xsl:message>
|
1128 |
+
</xsl:if>
|
1129 |
+
|
1130 |
+
<!-- lets at the top-level are implemented as parameters -->
|
1131 |
+
|
1132 |
+
<xsl:choose>
|
1133 |
+
<xsl:when test="parent::iso:schema">
|
1134 |
+
<!-- it is an error to have an empty param/@select because an XPath is expected -->
|
1135 |
+
<axsl:param name="{@name}" select="{@value}">
|
1136 |
+
<xsl:if test="string-length(@value) > 0">
|
1137 |
+
<xsl:attribute name="select"><xsl:value-of select="@value"/></xsl:attribute>
|
1138 |
+
</xsl:if>
|
1139 |
+
</axsl:param>
|
1140 |
+
</xsl:when>
|
1141 |
+
<xsl:otherwise>
|
1142 |
+
<axsl:variable name="{@name}" select="{@value}"/>
|
1143 |
+
</xsl:otherwise>
|
1144 |
+
</xsl:choose>
|
1145 |
+
|
1146 |
+
</xsl:template>
|
1147 |
+
|
1148 |
+
<!-- ISO NAME -->
|
1149 |
+
<xsl:template match="iso:name" mode="text">
|
1150 |
+
|
1151 |
+
<xsl:if test="@path">
|
1152 |
+
<xsl:call-template name="process-name">
|
1153 |
+
<xsl:with-param name="name" select="concat('name(',@path,')')"/>
|
1154 |
+
</xsl:call-template>
|
1155 |
+
</xsl:if>
|
1156 |
+
<xsl:if test="not(@path)">
|
1157 |
+
<xsl:call-template name="process-name">
|
1158 |
+
<xsl:with-param name="name" select="'name(.)'"/>
|
1159 |
+
</xsl:call-template>
|
1160 |
+
</xsl:if>
|
1161 |
+
<xsl:call-template name="IamEmpty" />
|
1162 |
+
</xsl:template>
|
1163 |
+
|
1164 |
+
<!-- ISO NS -->
|
1165 |
+
<!-- Namespace handling is XSLT is quite tricky and implementation dependent -->
|
1166 |
+
<xsl:template match="iso:ns">
|
1167 |
+
<xsl:call-template name="handle-namespace" />
|
1168 |
+
</xsl:template>
|
1169 |
+
|
1170 |
+
<!-- This template is just to provide the API hook -->
|
1171 |
+
<xsl:template match="iso:ns" mode="do-all-patterns" >
|
1172 |
+
<xsl:if test="not(@uri)">
|
1173 |
+
<xsl:message>Markup Error: no uri attribute in <ns></xsl:message>
|
1174 |
+
</xsl:if>
|
1175 |
+
<xsl:if test="not(@prefix)">
|
1176 |
+
<xsl:message>Markup Error: no prefix attribute in <ns></xsl:message>
|
1177 |
+
</xsl:if>
|
1178 |
+
<xsl:call-template name="IamEmpty" />
|
1179 |
+
<xsl:call-template name="process-ns" >
|
1180 |
+
<xsl:with-param name="prefix" select="@prefix"/>
|
1181 |
+
<xsl:with-param name="uri" select="@uri"/>
|
1182 |
+
</xsl:call-template>
|
1183 |
+
</xsl:template>
|
1184 |
+
|
1185 |
+
<!-- ISO P -->
|
1186 |
+
<xsl:template match="iso:schema/iso:p " mode="do-schema-p" >
|
1187 |
+
<xsl:call-template name="process-p">
|
1188 |
+
<xsl:with-param name="class" select="@class"/>
|
1189 |
+
<xsl:with-param name="icon" select="@icon"/>
|
1190 |
+
<xsl:with-param name="id" select="@id"/>
|
1191 |
+
<xsl:with-param name="lang" select="@xml:lang"/>
|
1192 |
+
</xsl:call-template>
|
1193 |
+
</xsl:template>
|
1194 |
+
<xsl:template match="iso:pattern/iso:p " mode="do-pattern-p" >
|
1195 |
+
<xsl:call-template name="process-p">
|
1196 |
+
<xsl:with-param name="class" select="@class"/>
|
1197 |
+
<xsl:with-param name="icon" select="@icon"/>
|
1198 |
+
<xsl:with-param name="id" select="@id"/>
|
1199 |
+
<xsl:with-param name="lang" select="@xml:lang"/>
|
1200 |
+
</xsl:call-template>
|
1201 |
+
</xsl:template>
|
1202 |
+
|
1203 |
+
<!-- Currently, iso:p in other position are not passed through to the API -->
|
1204 |
+
<xsl:template match="iso:phase/iso:p" />
|
1205 |
+
<xsl:template match="iso:p " priority="-1" />
|
1206 |
+
|
1207 |
+
<!-- ISO PATTERN -->
|
1208 |
+
<xsl:template match="iso:pattern" mode="do-all-patterns">
|
1209 |
+
<xsl:if test="($phase = '#ALL')
|
1210 |
+
or (../iso:phase[@id= $phase]/iso:active[@pattern= current()/@id])">
|
1211 |
+
<xsl:call-template name="process-pattern">
|
1212 |
+
<!-- the following select statement assumes that
|
1213 |
+
@id | sch:title returns node-set in document order:
|
1214 |
+
we want the title if it is there, otherwise the @id attribute -->
|
1215 |
+
<xsl:with-param name="name" select="(@id | iso:title )[last()]"/>
|
1216 |
+
<xsl:with-param name="is-a" select="''"/>
|
1217 |
+
|
1218 |
+
<!-- "Rich" properties -->
|
1219 |
+
<xsl:with-param name="fpi" select="@fpi"/>
|
1220 |
+
<xsl:with-param name="icon" select="@icon"/>
|
1221 |
+
<xsl:with-param name="id" select="@id"/>
|
1222 |
+
<xsl:with-param name="lang" select="@xml:lang"/>
|
1223 |
+
<xsl:with-param name="see" select="@see" />
|
1224 |
+
<xsl:with-param name="space" select="@xml:space" />
|
1225 |
+
</xsl:call-template>
|
1226 |
+
<xsl:choose>
|
1227 |
+
<xsl:when test="$select-contexts='key'">
|
1228 |
+
<axsl:apply-templates select="key('M','M{count(preceding-sibling::*)}')" mode="M{count(preceding-sibling::*)}"/>
|
1229 |
+
</xsl:when>
|
1230 |
+
<xsl:when test="$select-contexts='//'">
|
1231 |
+
<axsl:apply-templates mode="M{count(preceding-sibling::*)}">
|
1232 |
+
<xsl:attribute name="select">
|
1233 |
+
<xsl:text>//(</xsl:text>
|
1234 |
+
<xsl:for-each select="iso:rule/@context">
|
1235 |
+
<xsl:text>(</xsl:text>
|
1236 |
+
<xsl:value-of select="."/>
|
1237 |
+
<xsl:text>)</xsl:text>
|
1238 |
+
<xsl:if test="position()!=last()">|</xsl:if>
|
1239 |
+
</xsl:for-each>
|
1240 |
+
<xsl:text>)</xsl:text>
|
1241 |
+
<xsl:if test="$visit-text='false'">[not(self::text())]</xsl:if>
|
1242 |
+
</xsl:attribute>
|
1243 |
+
</axsl:apply-templates>
|
1244 |
+
</xsl:when>
|
1245 |
+
<xsl:otherwise>
|
1246 |
+
<axsl:apply-templates select="/" mode="M{count(preceding-sibling::*)}"/>
|
1247 |
+
</xsl:otherwise>
|
1248 |
+
</xsl:choose>
|
1249 |
+
</xsl:if>
|
1250 |
+
</xsl:template>
|
1251 |
+
|
1252 |
+
<xsl:template match="iso:pattern[@abstract='true']">
|
1253 |
+
|
1254 |
+
<xsl:message>Schema implementation error: This schema has abstract patterns, yet they are supposed to be preprocessed out already
|
1255 |
+
</xsl:message>
|
1256 |
+
</xsl:template>
|
1257 |
+
|
1258 |
+
<!-- Here is the template for the normal case of patterns -->
|
1259 |
+
<xsl:template match="iso:pattern[not(@abstract='true')]">
|
1260 |
+
|
1261 |
+
<xsl:if test="($phase = '#ALL')
|
1262 |
+
or (../iso:phase[@id= $phase]/iso:active[@pattern= current()/@id])">
|
1263 |
+
|
1264 |
+
<xsl:text> </xsl:text>
|
1265 |
+
<xsl:comment>PATTERN <xsl:value-of select="@id" /> <xsl:value-of select="iso:title" /> </xsl:comment><xsl:text> </xsl:text>
|
1266 |
+
<xsl:apply-templates />
|
1267 |
+
|
1268 |
+
<!-- DPC select-contexts test -->
|
1269 |
+
<xsl:if test="not($select-contexts)">
|
1270 |
+
<axsl:template match="text()" priority="-1" mode="M{count(preceding-sibling::*)}">
|
1271 |
+
<!-- strip characters -->
|
1272 |
+
</axsl:template>
|
1273 |
+
|
1274 |
+
<!-- DPC introduce context-xpath variable -->
|
1275 |
+
<axsl:template match="@*|node()"
|
1276 |
+
priority="-2"
|
1277 |
+
mode="M{ count(preceding-sibling::*) }">
|
1278 |
+
<axsl:apply-templates select="{$context-xpath}" mode="M{count(preceding-sibling::*)}"/>
|
1279 |
+
</axsl:template>
|
1280 |
+
</xsl:if>
|
1281 |
+
</xsl:if>
|
1282 |
+
</xsl:template>
|
1283 |
+
|
1284 |
+
<!-- ISO PHASE -->
|
1285 |
+
<xsl:template match="iso:phase" >
|
1286 |
+
<xsl:if test="not(@id)">
|
1287 |
+
<xsl:message>Markup Error: no id attribute in <phase></xsl:message>
|
1288 |
+
</xsl:if>
|
1289 |
+
<xsl:apply-templates/>
|
1290 |
+
</xsl:template>
|
1291 |
+
|
1292 |
+
<!-- ISO RULE -->
|
1293 |
+
<xsl:template match="iso:rule[not(@abstract='true')] ">
|
1294 |
+
<xsl:if test="not(@context)">
|
1295 |
+
<xsl:message>Markup Error: no context attribute in <rule></xsl:message>
|
1296 |
+
</xsl:if>
|
1297 |
+
<xsl:text> </xsl:text>
|
1298 |
+
<xsl:comment>RULE <xsl:value-of select="@id" /> </xsl:comment><xsl:text> </xsl:text>
|
1299 |
+
<xsl:if test="iso:title">
|
1300 |
+
<xsl:comment><xsl:value-of select="iso:title" /></xsl:comment>
|
1301 |
+
</xsl:if>
|
1302 |
+
<!-- DPC select-contexts -->
|
1303 |
+
<xsl:if test="$select-contexts='key'">
|
1304 |
+
<axsl:key name="M"
|
1305 |
+
match="{@context}"
|
1306 |
+
use="'M{count(../preceding-sibling::*)}'"/>
|
1307 |
+
</xsl:if>
|
1308 |
+
|
1309 |
+
|
1310 |
+
<!-- DPC priorities count up from 1000 not down from 4000 (templates in same priority order as before) -->
|
1311 |
+
<axsl:template match="{@context}"
|
1312 |
+
priority="{1000 + count(following-sibling::*)}" mode="M{count(../preceding-sibling::*)}">
|
1313 |
+
<xsl:call-template name="process-rule">
|
1314 |
+
<xsl:with-param name="context" select="@context"/>
|
1315 |
+
|
1316 |
+
<!-- "Rich" properties -->
|
1317 |
+
<xsl:with-param name="fpi" select="@fpi"/>
|
1318 |
+
<xsl:with-param name="icon" select="@icon"/>
|
1319 |
+
<xsl:with-param name="id" select="@id"/>
|
1320 |
+
<xsl:with-param name="lang" select="@xml:lang"/>
|
1321 |
+
<xsl:with-param name="see" select="@see" />
|
1322 |
+
<xsl:with-param name="space" select="@xml:space" />
|
1323 |
+
|
1324 |
+
<!-- "Linking" properties -->
|
1325 |
+
<xsl:with-param name="role" select="@role" />
|
1326 |
+
<xsl:with-param name="subject" select="@subject" />
|
1327 |
+
</xsl:call-template>
|
1328 |
+
<xsl:apply-templates/>
|
1329 |
+
<!-- DPC introduce context-xpath and select-contexts variables -->
|
1330 |
+
<xsl:if test="not($select-contexts)">
|
1331 |
+
<axsl:apply-templates select="{$context-xpath}" mode="M{count(../preceding-sibling::*)}"/>
|
1332 |
+
</xsl:if>
|
1333 |
+
</axsl:template>
|
1334 |
+
</xsl:template>
|
1335 |
+
|
1336 |
+
|
1337 |
+
<!-- ISO ABSTRACT RULE -->
|
1338 |
+
<xsl:template match="iso:rule[@abstract='true'] " >
|
1339 |
+
<xsl:if test=" not(@id)">
|
1340 |
+
<xsl:message>Markup Error: no id attribute on abstract <rule></xsl:message>
|
1341 |
+
</xsl:if>
|
1342 |
+
<xsl:if test="@context">
|
1343 |
+
<xsl:message>Markup Error: (2) context attribute on abstract <rule></xsl:message>
|
1344 |
+
</xsl:if>
|
1345 |
+
</xsl:template>
|
1346 |
+
|
1347 |
+
<xsl:template match="iso:rule[@abstract='true']"
|
1348 |
+
mode="extends" >
|
1349 |
+
<xsl:if test="@context">
|
1350 |
+
<xsl:message>Markup Error: context attribute on abstract <rule></xsl:message>
|
1351 |
+
</xsl:if>
|
1352 |
+
<xsl:apply-templates/>
|
1353 |
+
</xsl:template>
|
1354 |
+
|
1355 |
+
<!-- ISO SPAN -->
|
1356 |
+
<xsl:template match="iso:span" mode="text">
|
1357 |
+
<xsl:call-template name="process-span">
|
1358 |
+
<xsl:with-param name="class" select="@class"/>
|
1359 |
+
</xsl:call-template>
|
1360 |
+
</xsl:template>
|
1361 |
+
|
1362 |
+
<!-- ISO TITLE -->
|
1363 |
+
|
1364 |
+
<xsl:template match="iso:schema/iso:title" priority="1">
|
1365 |
+
<xsl:call-template name="process-schema-title" />
|
1366 |
+
</xsl:template>
|
1367 |
+
|
1368 |
+
|
1369 |
+
<xsl:template match="iso:title" >
|
1370 |
+
<xsl:call-template name="process-title" />
|
1371 |
+
</xsl:template>
|
1372 |
+
|
1373 |
+
|
1374 |
+
<!-- ISO VALUE-OF -->
|
1375 |
+
<xsl:template match="iso:value-of" mode="text" >
|
1376 |
+
<xsl:if test="not(@select)">
|
1377 |
+
<xsl:message>Markup Error: no select attribute in <value-of></xsl:message>
|
1378 |
+
</xsl:if>
|
1379 |
+
<xsl:call-template name="IamEmpty" />
|
1380 |
+
|
1381 |
+
<xsl:choose>
|
1382 |
+
<xsl:when test="@select">
|
1383 |
+
<xsl:call-template name="process-value-of">
|
1384 |
+
<xsl:with-param name="select" select="@select"/>
|
1385 |
+
</xsl:call-template>
|
1386 |
+
</xsl:when>
|
1387 |
+
<xsl:otherwise >
|
1388 |
+
<xsl:call-template name="process-value-of">
|
1389 |
+
<xsl:with-param name="select" select="'.'"/>
|
1390 |
+
</xsl:call-template>
|
1391 |
+
</xsl:otherwise>
|
1392 |
+
</xsl:choose>
|
1393 |
+
|
1394 |
+
</xsl:template>
|
1395 |
+
|
1396 |
+
|
1397 |
+
<!-- ============================================================== -->
|
1398 |
+
<!-- DEFAULT TEXT HANDLING -->
|
1399 |
+
<!-- ============================================================== -->
|
1400 |
+
<xsl:template match="text()" priority="-1" mode="do-keys">
|
1401 |
+
<!-- strip characters -->
|
1402 |
+
</xsl:template>
|
1403 |
+
<xsl:template match="text()" priority="-1" mode="do-all-patterns">
|
1404 |
+
<!-- strip characters -->
|
1405 |
+
</xsl:template>
|
1406 |
+
<xsl:template match="text()" priority="-1" mode="do-schema-p">
|
1407 |
+
<!-- strip characters -->
|
1408 |
+
</xsl:template>
|
1409 |
+
<xsl:template match="text()" priority="-1" mode="do-pattern-p">
|
1410 |
+
<!-- strip characters -->
|
1411 |
+
</xsl:template>
|
1412 |
+
|
1413 |
+
<xsl:template match="text()" priority="-1">
|
1414 |
+
<!-- Strip characters -->
|
1415 |
+
</xsl:template>
|
1416 |
+
|
1417 |
+
<xsl:template match="text()" mode="text">
|
1418 |
+
<xsl:value-of select="."/>
|
1419 |
+
</xsl:template>
|
1420 |
+
|
1421 |
+
<xsl:template match="text()" mode="inline-text">
|
1422 |
+
<xsl:value-of select="."/>
|
1423 |
+
</xsl:template>
|
1424 |
+
|
1425 |
+
<!-- ============================================================== -->
|
1426 |
+
<!-- UTILITY TEMPLATES -->
|
1427 |
+
<!-- ============================================================== -->
|
1428 |
+
<xsl:template name="IamEmpty">
|
1429 |
+
<xsl:if test="count( * )">
|
1430 |
+
<xsl:message>
|
1431 |
+
<xsl:text>Warning: </xsl:text>
|
1432 |
+
<xsl:value-of select="name(.)"/>
|
1433 |
+
<xsl:text> must not contain any child elements</xsl:text>
|
1434 |
+
</xsl:message>
|
1435 |
+
</xsl:if>
|
1436 |
+
</xsl:template>
|
1437 |
+
|
1438 |
+
<xsl:template name="diagnosticsSplit">
|
1439 |
+
<!-- Process at the current point the first of the <diagnostic> elements
|
1440 |
+
referred to parameter str, and then recurse -->
|
1441 |
+
<xsl:param name="str"/>
|
1442 |
+
<xsl:variable name="start">
|
1443 |
+
<xsl:choose>
|
1444 |
+
<xsl:when test="contains($str,' ')">
|
1445 |
+
<xsl:value-of select="substring-before($str,' ')"/>
|
1446 |
+
</xsl:when>
|
1447 |
+
<xsl:otherwise><xsl:value-of select="$str"/></xsl:otherwise>
|
1448 |
+
</xsl:choose>
|
1449 |
+
</xsl:variable>
|
1450 |
+
|
1451 |
+
<xsl:variable name="end">
|
1452 |
+
<xsl:if test="contains($str,' ')">
|
1453 |
+
<xsl:value-of select="substring-after($str,' ')"/>
|
1454 |
+
</xsl:if>
|
1455 |
+
</xsl:variable>
|
1456 |
+
|
1457 |
+
<!-- This works with all namespaces -->
|
1458 |
+
<xsl:if test="not(string-length(normalize-space($start)) = 0)
|
1459 |
+
and not(//iso:diagnostic[@id = $start])
|
1460 |
+
and not(//sch:diagnostic[@id = $start])
|
1461 |
+
and not(//diagnostic[@id = $start])">
|
1462 |
+
<xsl:message>Reference error: A diagnostic "<xsl:value-of select="string($start)"
|
1463 |
+
/>" has been referenced but is not declared</xsl:message>
|
1464 |
+
</xsl:if>
|
1465 |
+
|
1466 |
+
<xsl:if test="string-length(normalize-space($start)) > 0">
|
1467 |
+
<xsl:text> </xsl:text>
|
1468 |
+
<xsl:apply-templates
|
1469 |
+
select="//iso:diagnostic[@id = $start ]
|
1470 |
+
| //sch:diagnostic[@id = $start ]
|
1471 |
+
| //diagnostic[@id= $start ]"/>
|
1472 |
+
</xsl:if>
|
1473 |
+
|
1474 |
+
<xsl:if test="not($end='')">
|
1475 |
+
<xsl:call-template name="diagnosticsSplit">
|
1476 |
+
<xsl:with-param name="str" select="$end"/>
|
1477 |
+
</xsl:call-template>
|
1478 |
+
</xsl:if>
|
1479 |
+
</xsl:template>
|
1480 |
+
|
1481 |
+
<!-- It would be nice to use this but xsl:namespace does not
|
1482 |
+
allow a fallback -->
|
1483 |
+
<!--xsl:template name="handle-namespace" version="2.0">
|
1484 |
+
<xsl:namespace name="{@prefix}" select="@uri">
|
1485 |
+
</xsl:template-->
|
1486 |
+
|
1487 |
+
<xsl:template name="handle-namespace">
|
1488 |
+
<!-- experimental code from http://eccnet.eccnet.com/pipermail/schematron-love-in/2006-June/000104.html -->
|
1489 |
+
<!-- Handle namespaces differently for exslt systems, msxml, and default, only using XSLT1 syntax -->
|
1490 |
+
<!-- For more info see http://fgeorges.blogspot.com/2007/01/creating-namespace-nodes-in-xslt-10.html -->
|
1491 |
+
<xsl:choose>
|
1492 |
+
<!-- The following code works for XSLT1 -->
|
1493 |
+
<xsl:when test="function-available('exsl:node-set')">
|
1494 |
+
<xsl:variable name="ns-dummy-elements">
|
1495 |
+
<xsl:element name="{@prefix}:dummy" namespace="{@uri}"/>
|
1496 |
+
</xsl:variable>
|
1497 |
+
<xsl:variable name="p" select="@prefix"/>
|
1498 |
+
<xsl:copy-of select="exsl:node-set($ns-dummy-elements)
|
1499 |
+
/*/namespace::*[local-name()=$p]"/>
|
1500 |
+
</xsl:when>
|
1501 |
+
|
1502 |
+
<!-- End XSLT1 code -->
|
1503 |
+
|
1504 |
+
<!-- Not tested yet
|
1505 |
+
<xsl:when test="function-available('msxsl:node-set')">
|
1506 |
+
<xsl:variable name="ns-dummy-elements">
|
1507 |
+
<xsl:element name="{ $prefix }:e" namespace="{ $uri }"/>
|
1508 |
+
</xsl:variable>
|
1509 |
+
<xsl:copy-of select="msxsl:node-set($ns-dummy-elements)/*/namespace::*"/>
|
1510 |
+
</xsl:when>
|
1511 |
+
-->
|
1512 |
+
|
1513 |
+
<xsl:when test="@prefix = 'xsl' ">
|
1514 |
+
<!-- Do not generate dummy attributes with the xsl: prefix, as these
|
1515 |
+
are errors against XSLT, because we presume that the output
|
1516 |
+
stylesheet uses the xsl prefix. In any case, there would already
|
1517 |
+
be a namespace declaration for the XSLT namespace generated
|
1518 |
+
automatically, presumably using "xsl:".
|
1519 |
+
-->
|
1520 |
+
</xsl:when>
|
1521 |
+
|
1522 |
+
<xsl:when test="@uri = 'http://www.w3.org/1999/XSL/Transform'">
|
1523 |
+
<xsl:message terminate="yes">
|
1524 |
+
<xsl:text>Using the XSLT namespace with a prefix other than "xsl" in </xsl:text>
|
1525 |
+
<xsl:text>Schematron rules is not supported </xsl:text>
|
1526 |
+
<xsl:text>in this processor: </xsl:text>
|
1527 |
+
<xsl:value-of select="system-property('xsl:vendor')"/>
|
1528 |
+
</xsl:message>
|
1529 |
+
</xsl:when>
|
1530 |
+
|
1531 |
+
<xsl:otherwise>
|
1532 |
+
<xsl:attribute name="{concat(@prefix,':dummy-for-xmlns')}" namespace="{@uri}" />
|
1533 |
+
|
1534 |
+
</xsl:otherwise>
|
1535 |
+
</xsl:choose>
|
1536 |
+
|
1537 |
+
|
1538 |
+
</xsl:template>
|
1539 |
+
|
1540 |
+
<!-- ============================================================== -->
|
1541 |
+
<!-- UNEXPECTED ELEMENTS -->
|
1542 |
+
<!-- ============================================================== -->
|
1543 |
+
|
1544 |
+
<xsl:template match="iso:*" priority="-2">
|
1545 |
+
<xsl:message>
|
1546 |
+
<xsl:text>Error: unrecognized element in ISO Schematron namespace: check spelling
|
1547 |
+
and capitalization</xsl:text>
|
1548 |
+
<xsl:value-of select="name(.)"/>
|
1549 |
+
</xsl:message>
|
1550 |
+
</xsl:template>
|
1551 |
+
|
1552 |
+
|
1553 |
+
<!-- Swallow old namespace elements: there is an upfront test for them elsewhere -->
|
1554 |
+
<xsl:template match="sch:*" priority="-2" />
|
1555 |
+
|
1556 |
+
<xsl:template match="*" priority="-3">
|
1557 |
+
<xsl:choose>
|
1558 |
+
<xsl:when test=" $allow-foreign = 'false' ">
|
1559 |
+
<xsl:message>
|
1560 |
+
<xsl:text>Warning: unrecognized element </xsl:text>
|
1561 |
+
<xsl:value-of select="name(.)"/>
|
1562 |
+
</xsl:message>
|
1563 |
+
</xsl:when>
|
1564 |
+
<xsl:otherwise>
|
1565 |
+
<xsl:copy-of select="." />
|
1566 |
+
</xsl:otherwise>
|
1567 |
+
</xsl:choose>
|
1568 |
+
</xsl:template>
|
1569 |
+
|
1570 |
+
<xsl:template match="iso:*" mode="text" priority="-2" />
|
1571 |
+
<xsl:template match="*" mode="text" priority="-3">
|
1572 |
+
<xsl:choose>
|
1573 |
+
<xsl:when test=" $allow-foreign = 'false' ">
|
1574 |
+
<xsl:message>
|
1575 |
+
<xsl:text>Warning: unrecognized element </xsl:text>
|
1576 |
+
<xsl:value-of select="name(.)"/>
|
1577 |
+
</xsl:message>
|
1578 |
+
</xsl:when>
|
1579 |
+
<xsl:otherwise>
|
1580 |
+
<xsl:copy-of select="." />
|
1581 |
+
</xsl:otherwise>
|
1582 |
+
</xsl:choose>
|
1583 |
+
</xsl:template>
|
1584 |
+
|
1585 |
+
<!-- ============================================================== -->
|
1586 |
+
<!-- DEFAULT NAMED TEMPLATES -->
|
1587 |
+
<!-- These are the actions that are performed unless overridden -->
|
1588 |
+
<!-- ============================================================== -->
|
1589 |
+
|
1590 |
+
<xsl:template name="process-prolog"/>
|
1591 |
+
<!-- no params -->
|
1592 |
+
|
1593 |
+
<xsl:template name="process-root">
|
1594 |
+
<xsl:param name="contents"/>
|
1595 |
+
<xsl:param name="id" />
|
1596 |
+
<xsl:param name="version" />
|
1597 |
+
<xsl:param name="schemaVersion" />
|
1598 |
+
<xsl:param name="queryBinding" />
|
1599 |
+
<xsl:param name="title" />
|
1600 |
+
|
1601 |
+
|
1602 |
+
<!-- "Rich" parameters -->
|
1603 |
+
<xsl:param name="fpi" />
|
1604 |
+
<xsl:param name="icon" />
|
1605 |
+
<xsl:param name="lang" />
|
1606 |
+
<xsl:param name="see" />
|
1607 |
+
<xsl:param name="space" />
|
1608 |
+
|
1609 |
+
<xsl:copy-of select="$contents"/>
|
1610 |
+
</xsl:template>
|
1611 |
+
|
1612 |
+
<xsl:template name="process-assert">
|
1613 |
+
|
1614 |
+
<xsl:param name="test"/>
|
1615 |
+
<xsl:param name="diagnostics" />
|
1616 |
+
<xsl:param name="id" />
|
1617 |
+
<xsl:param name="flag" />
|
1618 |
+
|
1619 |
+
<!-- "Linkable" parameters -->
|
1620 |
+
<xsl:param name="role"/>
|
1621 |
+
<xsl:param name="subject"/>
|
1622 |
+
|
1623 |
+
<!-- "Rich" parameters -->
|
1624 |
+
<xsl:param name="fpi" />
|
1625 |
+
<xsl:param name="icon" />
|
1626 |
+
<xsl:param name="lang" />
|
1627 |
+
<xsl:param name="see" />
|
1628 |
+
<xsl:param name="space" />
|
1629 |
+
|
1630 |
+
|
1631 |
+
<xsl:call-template name="process-message">
|
1632 |
+
<xsl:with-param name="pattern" select="$test"/>
|
1633 |
+
<xsl:with-param name="role" select="$role"/>
|
1634 |
+
</xsl:call-template>
|
1635 |
+
|
1636 |
+
|
1637 |
+
</xsl:template>
|
1638 |
+
|
1639 |
+
<xsl:template name="process-report">
|
1640 |
+
<xsl:param name="test"/>
|
1641 |
+
<xsl:param name="diagnostics" />
|
1642 |
+
<xsl:param name="id" />
|
1643 |
+
<xsl:param name="flag" />
|
1644 |
+
|
1645 |
+
<!-- "Linkable" parameters -->
|
1646 |
+
<xsl:param name="role"/>
|
1647 |
+
<xsl:param name="subject"/>
|
1648 |
+
|
1649 |
+
<!-- "Rich" parameters -->
|
1650 |
+
<xsl:param name="fpi" />
|
1651 |
+
<xsl:param name="icon" />
|
1652 |
+
<xsl:param name="lang" />
|
1653 |
+
<xsl:param name="see" />
|
1654 |
+
<xsl:param name="space" />
|
1655 |
+
|
1656 |
+
<xsl:call-template name="process-message">
|
1657 |
+
<xsl:with-param name="pattern" select="$test"/>
|
1658 |
+
<xsl:with-param name="role" select="$role"/>
|
1659 |
+
</xsl:call-template>
|
1660 |
+
</xsl:template>
|
1661 |
+
|
1662 |
+
<xsl:template name="process-diagnostic">
|
1663 |
+
<xsl:param name="id" />
|
1664 |
+
|
1665 |
+
<!-- "Rich" parameters -->
|
1666 |
+
<xsl:param name="fpi" />
|
1667 |
+
<xsl:param name="icon" />
|
1668 |
+
<xsl:param name="lang" />
|
1669 |
+
<xsl:param name="see" />
|
1670 |
+
<xsl:param name="space" />
|
1671 |
+
|
1672 |
+
<!-- We generate too much whitespace rather than risking concatenation -->
|
1673 |
+
<axsl:text> </axsl:text>
|
1674 |
+
<xsl:apply-templates mode="text"/>
|
1675 |
+
<axsl:text> </axsl:text>
|
1676 |
+
</xsl:template>
|
1677 |
+
|
1678 |
+
<xsl:template name="process-dir">
|
1679 |
+
<xsl:param name="value" />
|
1680 |
+
|
1681 |
+
<!-- We generate too much whitespace rather than risking concatenation -->
|
1682 |
+
<axsl:text> </axsl:text>
|
1683 |
+
<xsl:apply-templates mode="inline-text"/>
|
1684 |
+
<axsl:text> </axsl:text>
|
1685 |
+
</xsl:template>
|
1686 |
+
|
1687 |
+
<xsl:template name="process-emph">
|
1688 |
+
<!-- We generate too much whitespace rather than risking concatenation -->
|
1689 |
+
<axsl:text> </axsl:text>
|
1690 |
+
<xsl:apply-templates mode="inline-text"/>
|
1691 |
+
<axsl:text> </axsl:text>
|
1692 |
+
</xsl:template>
|
1693 |
+
|
1694 |
+
<xsl:template name="process-name">
|
1695 |
+
<xsl:param name="name"/>
|
1696 |
+
|
1697 |
+
<!-- We generate too much whitespace rather than risking concatenation -->
|
1698 |
+
<axsl:text> </axsl:text>
|
1699 |
+
<axsl:value-of select="{$name}"/>
|
1700 |
+
<axsl:text> </axsl:text>
|
1701 |
+
|
1702 |
+
</xsl:template>
|
1703 |
+
|
1704 |
+
<xsl:template name="process-ns" >
|
1705 |
+
<!-- Note that process-ns is for reporting. The sch:ns elements are
|
1706 |
+
independently used in the sch:schema template to provide namespace bindings -->
|
1707 |
+
<xsl:param name="prefix"/>
|
1708 |
+
<xsl:param name="uri" />
|
1709 |
+
</xsl:template>
|
1710 |
+
|
1711 |
+
<xsl:template name="process-p">
|
1712 |
+
<xsl:param name="id" />
|
1713 |
+
<xsl:param name="class" />
|
1714 |
+
<xsl:param name="icon" />
|
1715 |
+
<xsl:param name="lang" />
|
1716 |
+
</xsl:template>
|
1717 |
+
|
1718 |
+
<xsl:template name="process-pattern">
|
1719 |
+
<xsl:param name="id" />
|
1720 |
+
<xsl:param name="name" />
|
1721 |
+
<xsl:param name="is-a" />
|
1722 |
+
|
1723 |
+
<!-- "Rich" parameters -->
|
1724 |
+
<xsl:param name="fpi" />
|
1725 |
+
<xsl:param name="icon" />
|
1726 |
+
<xsl:param name="lang" />
|
1727 |
+
<xsl:param name="see" />
|
1728 |
+
<xsl:param name="space" />
|
1729 |
+
</xsl:template>
|
1730 |
+
|
1731 |
+
|
1732 |
+
<xsl:template name="process-rule">
|
1733 |
+
<xsl:param name="context" />
|
1734 |
+
|
1735 |
+
<xsl:param name="id" />
|
1736 |
+
<xsl:param name="flag" />
|
1737 |
+
|
1738 |
+
<!-- "Linkable" parameters -->
|
1739 |
+
<xsl:param name="role"/>
|
1740 |
+
<xsl:param name="subject"/>
|
1741 |
+
|
1742 |
+
<!-- "Rich" parameters -->
|
1743 |
+
<xsl:param name="fpi" />
|
1744 |
+
<xsl:param name="icon" />
|
1745 |
+
<xsl:param name="lang" />
|
1746 |
+
<xsl:param name="see" />
|
1747 |
+
<xsl:param name="space" />
|
1748 |
+
</xsl:template>
|
1749 |
+
|
1750 |
+
<xsl:template name="process-span" >
|
1751 |
+
<xsl:param name="class" />
|
1752 |
+
|
1753 |
+
<!-- We generate too much whitespace rather than risking concatenation -->
|
1754 |
+
<axsl:text> </axsl:text>
|
1755 |
+
<xsl:apply-templates mode="inline-text"/>
|
1756 |
+
<axsl:text> </axsl:text>
|
1757 |
+
</xsl:template>
|
1758 |
+
|
1759 |
+
<xsl:template name="process-title" >
|
1760 |
+
<xsl:param name="class" />
|
1761 |
+
<xsl:call-template name="process-p">
|
1762 |
+
<xsl:with-param name="class">title</xsl:with-param>
|
1763 |
+
</xsl:call-template>
|
1764 |
+
</xsl:template>
|
1765 |
+
|
1766 |
+
<xsl:template name="process-schema-title" >
|
1767 |
+
<xsl:param name="class" />
|
1768 |
+
<xsl:call-template name="process-title">
|
1769 |
+
<xsl:with-param name="class">schema-title</xsl:with-param>
|
1770 |
+
</xsl:call-template>
|
1771 |
+
</xsl:template>
|
1772 |
+
|
1773 |
+
<xsl:template name="process-value-of">
|
1774 |
+
<xsl:param name="select"/>
|
1775 |
+
|
1776 |
+
<!-- We generate too much whitespace rather than risking concatenation -->
|
1777 |
+
<axsl:text> </axsl:text>
|
1778 |
+
<axsl:value-of select="{$select}"/>
|
1779 |
+
<axsl:text> </axsl:text>
|
1780 |
+
</xsl:template>
|
1781 |
+
|
1782 |
+
<!-- default output action: the simplest customization is to just override this -->
|
1783 |
+
<xsl:template name="process-message">
|
1784 |
+
<xsl:param name="pattern" />
|
1785 |
+
<xsl:param name="role" />
|
1786 |
+
|
1787 |
+
<xsl:apply-templates mode="text"/>
|
1788 |
+
<xsl:if test=" $message-newline = 'true'" >
|
1789 |
+
<axsl:value-of select="string(' ')"/>
|
1790 |
+
</xsl:if>
|
1791 |
+
|
1792 |
+
</xsl:template>
|
1793 |
+
</xsl:stylesheet>
|
1794 |
+
|
1795 |
+
|
1796 |
+
|
llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_svrl_for_xslt1.xsl
ADDED
@@ -0,0 +1,588 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<?xml version="1.0" ?>
|
2 |
+
<!--
|
3 |
+
ISO_SVRL.xsl
|
4 |
+
|
5 |
+
Implementation of Schematron Validation Report Language from ISO Schematron
|
6 |
+
ISO/IEC 19757 Document Schema Definition Languages (DSDL)
|
7 |
+
Part 3: Rule-based validation Schematron
|
8 |
+
Annex D: Schematron Validation Report Language
|
9 |
+
|
10 |
+
This ISO Standard is available free as a Publicly Available Specification in PDF from ISO.
|
11 |
+
Also see www.schematron.com for drafts and other information.
|
12 |
+
|
13 |
+
This implementation of SVRL is designed to run with the "Skeleton" implementation
|
14 |
+
of Schematron which Oliver Becker devised. The skeleton code provides a
|
15 |
+
Schematron implementation but with named templates for handling all output;
|
16 |
+
the skeleton provides basic templates for output using this API, but client
|
17 |
+
validators can be written to import the skeleton and override the default output
|
18 |
+
templates as required. (In order to understand this, you must understand that
|
19 |
+
a named template such as "process-assert" in this XSLT stylesheet overrides and
|
20 |
+
replaces any template with the same name in the imported skeleton XSLT file.)
|
21 |
+
|
22 |
+
The other important thing to understand in this code is that there are different
|
23 |
+
versions of the Schematron skeleton. These track the development of Schematron through
|
24 |
+
Schematron 1.5, Schematron 1.6 and now ISO Schematron. One only skeleton must be
|
25 |
+
imported. The code has templates for the different skeletons commented out for
|
26 |
+
convenience. ISO Schematron has a different namespace than Schematron 1.5 and 1.6;
|
27 |
+
so the ISO Schematron skeleton has been written itself with an optional import
|
28 |
+
statement to in turn import the Schematron 1.6 skeleton. This will allow you to
|
29 |
+
validate with schemas from either namespace.
|
30 |
+
|
31 |
+
|
32 |
+
History:
|
33 |
+
2009-03-18
|
34 |
+
* Fix atrribute with space "see " which generates wrong name in some processors
|
35 |
+
2008-08-11
|
36 |
+
* RJ Fix attribute/@select which saxon allows in XSLT 1
|
37 |
+
2008-08-07
|
38 |
+
* RJ Add output-encoding attribute to specify final encoding to use
|
39 |
+
* Alter allow-foreign functionality so that Schematron span, emph and dir elements make
|
40 |
+
it to the output, for better formatting and because span can be used to mark up
|
41 |
+
semantically interesting information embedded in diagnostics, which reduces the
|
42 |
+
need to extend SVRL itself
|
43 |
+
* Diagnostic-reference had an invalid attribute @id that duplicated @diagnostic: removed
|
44 |
+
2008-08-06
|
45 |
+
* RJ Fix invalid output: svrl:diagnostic-reference is not contained in an svrl:text
|
46 |
+
* Output comment to SVRL file giving filename if available (from command-line parameter)
|
47 |
+
2008-08-04
|
48 |
+
* RJ move sch: prefix to schold: prefix to prevent confusion (we want people to
|
49 |
+
be able to switch from old namespace to new namespace without changing the
|
50 |
+
sch: prefix, so it is better to keep that prefix completely out of the XSLT)
|
51 |
+
* Extra signature fixes (PH)
|
52 |
+
2008-08-03
|
53 |
+
* Repair missing class parameter on process-p
|
54 |
+
2008-07-31
|
55 |
+
* Update skeleton names
|
56 |
+
2007-04-03
|
57 |
+
* Add option generate-fired-rule (RG)
|
58 |
+
2007-02-07
|
59 |
+
* Prefer true|false for parameters. But allow yes|no on some old for compatability
|
60 |
+
* DP Diagnostics output to svrl:text. Diagnosis put out after assertion text.
|
61 |
+
* Removed non-SVRL elements and attributes: better handled as an extra layer that invokes this one
|
62 |
+
* Add more formal parameters
|
63 |
+
* Correct confusion between $schemaVersion and $queryBinding
|
64 |
+
* Indent
|
65 |
+
* Validate against RNC schemas for XSLT 1 and 2 (with regex tests removed)
|
66 |
+
* Validate output with UniversalTest.sch against RNC schema for ISO SVRL
|
67 |
+
|
68 |
+
2007-02-01
|
69 |
+
* DP. Update formal parameters of overriding named templates to handle more attributes.
|
70 |
+
* DP. Refactor handling of rich and linkable parameters to a named template.
|
71 |
+
|
72 |
+
2007-01-22
|
73 |
+
* DP change svrl:ns to svrl:ns-in-attribute-value
|
74 |
+
* Change default when no queryBinding from "unknown" to "xslt"
|
75 |
+
|
76 |
+
2007-01-18:
|
77 |
+
* Improve documentation
|
78 |
+
* KH Add command-line options to generate paths or not
|
79 |
+
* Use axsl:attribute rather than xsl:attribute to shut XSLT2 up
|
80 |
+
* Add extra command-line options to pass to the iso_schematron_skeleton
|
81 |
+
|
82 |
+
2006-12-01: iso_svrl.xsl Rick Jelliffe,
|
83 |
+
* update namespace,
|
84 |
+
* update phase handling,
|
85 |
+
* add flag param to process-assert and process-report & @ flag on output
|
86 |
+
|
87 |
+
2001: Conformance1-5.xsl Rick Jelliffe,
|
88 |
+
* Created, using the skeleton code contributed by Oliver Becker
|
89 |
+
-->
|
90 |
+
<!--
|
91 |
+
Derived from Conformance1-5.xsl.
|
92 |
+
|
93 |
+
Copyright (c) 2001, 2006 Rick Jelliffe and Academia Sinica Computing Center, Taiwan
|
94 |
+
|
95 |
+
This software is provided 'as-is', without any express or implied warranty.
|
96 |
+
In no event will the authors be held liable for any damages arising from
|
97 |
+
the use of this software.
|
98 |
+
|
99 |
+
Permission is granted to anyone to use this software for any purpose,
|
100 |
+
including commercial applications, and to alter it and redistribute it freely,
|
101 |
+
subject to the following restrictions:
|
102 |
+
|
103 |
+
1. The origin of this software must not be misrepresented; you must not claim
|
104 |
+
that you wrote the original software. If you use this software in a product,
|
105 |
+
an acknowledgment in the product documentation would be appreciated but is
|
106 |
+
not required.
|
107 |
+
|
108 |
+
2. Altered source versions must be plainly marked as such, and must not be
|
109 |
+
misrepresented as being the original software.
|
110 |
+
|
111 |
+
3. This notice may not be removed or altered from any source distribution.
|
112 |
+
-->
|
113 |
+
|
114 |
+
<!-- Ideas nabbed from schematrons by Francis N., Miloslav N. and David C. -->
|
115 |
+
|
116 |
+
<!-- The command-line parameters are:
|
117 |
+
phase NMTOKEN | "#ALL" (default) Select the phase for validation
|
118 |
+
allow-foreign "true" | "false" (default) Pass non-Schematron elements and rich markup to the generated stylesheet
|
119 |
+
diagnose= true | false|yes|no Add the diagnostics to the assertion test in reports (yes|no are obsolete)
|
120 |
+
generate-paths=true|false|yes|no generate the @location attribute with XPaths (yes|no are obsolete)
|
121 |
+
sch.exslt.imports semi-colon delimited string of filenames for some EXSLT implementations
|
122 |
+
optimize "visit-no-attributes" Use only when the schema has no attributes as the context nodes
|
123 |
+
generate-fired-rule "true"(default) | "false" Generate fired-rule elements
|
124 |
+
|
125 |
+
-->
|
126 |
+
|
127 |
+
<xsl:stylesheet
|
128 |
+
version="1.0"
|
129 |
+
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
|
130 |
+
xmlns:xs="http://www.w3.org/2001/XMLSchema"
|
131 |
+
xmlns:axsl="http://www.w3.org/1999/XSL/TransformAlias"
|
132 |
+
xmlns:schold="http://www.ascc.net/xml/schematron"
|
133 |
+
xmlns:iso="http://purl.oclc.org/dsdl/schematron"
|
134 |
+
xmlns:svrl="http://purl.oclc.org/dsdl/svrl"
|
135 |
+
>
|
136 |
+
|
137 |
+
<!-- Select the import statement and adjust the path as
|
138 |
+
necessary for your system.
|
139 |
+
If not XSLT2 then also remove svrl:active-pattern/@document="{document-uri()}" from process-pattern()
|
140 |
+
-->
|
141 |
+
<!--
|
142 |
+
<xsl:import href="iso_schematron_skeleton_for_saxon.xsl"/>
|
143 |
+
-->
|
144 |
+
|
145 |
+
<xsl:import href="iso_schematron_skeleton_for_xslt1.xsl"/>
|
146 |
+
<!--
|
147 |
+
<xsl:import href="iso_schematron_skeleton.xsl"/>
|
148 |
+
<xsl:import href="skeleton1-5.xsl"/>
|
149 |
+
<xsl:import href="skeleton1-6.xsl"/>
|
150 |
+
-->
|
151 |
+
|
152 |
+
<xsl:param name="diagnose" >true</xsl:param>
|
153 |
+
<xsl:param name="phase" >
|
154 |
+
<xsl:choose>
|
155 |
+
<!-- Handle Schematron 1.5 and 1.6 phases -->
|
156 |
+
<xsl:when test="//schold:schema/@defaultPhase">
|
157 |
+
<xsl:value-of select="//schold:schema/@defaultPhase"/>
|
158 |
+
</xsl:when>
|
159 |
+
<!-- Handle ISO Schematron phases -->
|
160 |
+
<xsl:when test="//iso:schema/@defaultPhase">
|
161 |
+
<xsl:value-of select="//iso:schema/@defaultPhase"/>
|
162 |
+
</xsl:when>
|
163 |
+
<xsl:otherwise>#ALL</xsl:otherwise>
|
164 |
+
</xsl:choose>
|
165 |
+
</xsl:param>
|
166 |
+
<xsl:param name="allow-foreign" >false</xsl:param>
|
167 |
+
<xsl:param name="generate-paths" >true</xsl:param>
|
168 |
+
<xsl:param name="generate-fired-rule" >true</xsl:param>
|
169 |
+
<xsl:param name="optimize"/>
|
170 |
+
|
171 |
+
<xsl:param name="output-encoding" ></xsl:param>
|
172 |
+
|
173 |
+
<!-- e.g. saxon file.xml file.xsl "sch.exslt.imports=.../string.xsl;.../math.xsl" -->
|
174 |
+
<xsl:param name="sch.exslt.imports" />
|
175 |
+
|
176 |
+
|
177 |
+
|
178 |
+
<!-- Experimental: If this file called, then must be generating svrl -->
|
179 |
+
<xsl:variable name="svrlTest" select="true()" />
|
180 |
+
|
181 |
+
|
182 |
+
|
183 |
+
<!-- ================================================================ -->
|
184 |
+
|
185 |
+
<xsl:template name="process-prolog">
|
186 |
+
<axsl:output method="xml" omit-xml-declaration="no" standalone="yes"
|
187 |
+
indent="yes">
|
188 |
+
<xsl:if test=" string-length($output-encoding) > 0">
|
189 |
+
<xsl:attribute name="encoding"><xsl:value-of select=" $output-encoding" /></xsl:attribute>
|
190 |
+
</xsl:if>
|
191 |
+
</axsl:output>
|
192 |
+
|
193 |
+
</xsl:template>
|
194 |
+
|
195 |
+
<!-- Overrides skeleton.xsl -->
|
196 |
+
<xsl:template name="process-root">
|
197 |
+
<xsl:param name="title"/>
|
198 |
+
<xsl:param name="contents" />
|
199 |
+
<xsl:param name="queryBinding" >xslt1</xsl:param>
|
200 |
+
<xsl:param name="schemaVersion" />
|
201 |
+
<xsl:param name="id" />
|
202 |
+
<xsl:param name="version"/>
|
203 |
+
<!-- "Rich" parameters -->
|
204 |
+
<xsl:param name="fpi" />
|
205 |
+
<xsl:param name="icon" />
|
206 |
+
<xsl:param name="lang" />
|
207 |
+
<xsl:param name="see" />
|
208 |
+
<xsl:param name="space" />
|
209 |
+
|
210 |
+
<svrl:schematron-output title="{$title}" schemaVersion="{$schemaVersion}" >
|
211 |
+
<xsl:if test=" string-length( normalize-space( $phase )) > 0 and
|
212 |
+
not( normalize-space( $phase ) = '#ALL') ">
|
213 |
+
<axsl:attribute name="phase">
|
214 |
+
<xsl:value-of select=" $phase " />
|
215 |
+
</axsl:attribute>
|
216 |
+
</xsl:if>
|
217 |
+
<xsl:if test=" $allow-foreign = 'true'">
|
218 |
+
</xsl:if>
|
219 |
+
<xsl:if test=" $allow-foreign = 'true'">
|
220 |
+
|
221 |
+
<xsl:call-template name='richParms'>
|
222 |
+
<xsl:with-param name="fpi" select="$fpi" />
|
223 |
+
<xsl:with-param name="icon" select="$icon"/>
|
224 |
+
<xsl:with-param name="lang" select="$lang"/>
|
225 |
+
<xsl:with-param name="see" select="$see" />
|
226 |
+
<xsl:with-param name="space" select="$space" />
|
227 |
+
</xsl:call-template>
|
228 |
+
</xsl:if>
|
229 |
+
|
230 |
+
<axsl:comment><axsl:value-of select="$archiveDirParameter"/>  
|
231 |
+
<axsl:value-of select="$archiveNameParameter"/>  
|
232 |
+
<axsl:value-of select="$fileNameParameter"/>  
|
233 |
+
<axsl:value-of select="$fileDirParameter"/></axsl:comment>
|
234 |
+
|
235 |
+
|
236 |
+
<xsl:apply-templates mode="do-schema-p" />
|
237 |
+
<xsl:copy-of select="$contents" />
|
238 |
+
</svrl:schematron-output>
|
239 |
+
</xsl:template>
|
240 |
+
|
241 |
+
|
242 |
+
<xsl:template name="process-assert">
|
243 |
+
<xsl:param name="test"/>
|
244 |
+
<xsl:param name="diagnostics" />
|
245 |
+
<xsl:param name="id" />
|
246 |
+
<xsl:param name="flag" />
|
247 |
+
<!-- "Linkable" parameters -->
|
248 |
+
<xsl:param name="role"/>
|
249 |
+
<xsl:param name="subject"/>
|
250 |
+
<!-- "Rich" parameters -->
|
251 |
+
<xsl:param name="fpi" />
|
252 |
+
<xsl:param name="icon" />
|
253 |
+
<xsl:param name="lang" />
|
254 |
+
<xsl:param name="see" />
|
255 |
+
<xsl:param name="space" />
|
256 |
+
<svrl:failed-assert test="{$test}" >
|
257 |
+
<xsl:if test="string-length( $id ) > 0">
|
258 |
+
<axsl:attribute name="id">
|
259 |
+
<xsl:value-of select=" $id " />
|
260 |
+
</axsl:attribute>
|
261 |
+
</xsl:if>
|
262 |
+
<xsl:if test=" string-length( $flag ) > 0">
|
263 |
+
<axsl:attribute name="flag">
|
264 |
+
<xsl:value-of select=" $flag " />
|
265 |
+
</axsl:attribute>
|
266 |
+
</xsl:if>
|
267 |
+
<!-- Process rich attributes. -->
|
268 |
+
<xsl:call-template name="richParms">
|
269 |
+
<xsl:with-param name="fpi" select="$fpi"/>
|
270 |
+
<xsl:with-param name="icon" select="$icon"/>
|
271 |
+
<xsl:with-param name="lang" select="$lang"/>
|
272 |
+
<xsl:with-param name="see" select="$see" />
|
273 |
+
<xsl:with-param name="space" select="$space" />
|
274 |
+
</xsl:call-template>
|
275 |
+
<xsl:call-template name='linkableParms'>
|
276 |
+
<xsl:with-param name="role" select="$role" />
|
277 |
+
<xsl:with-param name="subject" select="$subject"/>
|
278 |
+
</xsl:call-template>
|
279 |
+
<xsl:if test=" $generate-paths = 'true' or $generate-paths= 'yes' ">
|
280 |
+
<!-- true/false is the new way -->
|
281 |
+
<axsl:attribute name="location">
|
282 |
+
<axsl:apply-templates select="." mode="schematron-get-full-path"/>
|
283 |
+
</axsl:attribute>
|
284 |
+
</xsl:if>
|
285 |
+
|
286 |
+
<svrl:text>
|
287 |
+
<xsl:apply-templates mode="text" />
|
288 |
+
|
289 |
+
</svrl:text>
|
290 |
+
<xsl:if test="$diagnose = 'yes' or $diagnose= 'true' ">
|
291 |
+
<!-- true/false is the new way -->
|
292 |
+
<xsl:call-template name="diagnosticsSplit">
|
293 |
+
<xsl:with-param name="str" select="$diagnostics"/>
|
294 |
+
</xsl:call-template>
|
295 |
+
</xsl:if>
|
296 |
+
</svrl:failed-assert>
|
297 |
+
</xsl:template>
|
298 |
+
|
299 |
+
<xsl:template name="process-report">
|
300 |
+
<xsl:param name="id"/>
|
301 |
+
<xsl:param name="test"/>
|
302 |
+
<xsl:param name="diagnostics"/>
|
303 |
+
<xsl:param name="flag" />
|
304 |
+
<!-- "Linkable" parameters -->
|
305 |
+
<xsl:param name="role"/>
|
306 |
+
<xsl:param name="subject"/>
|
307 |
+
<!-- "Rich" parameters -->
|
308 |
+
<xsl:param name="fpi" />
|
309 |
+
<xsl:param name="icon" />
|
310 |
+
<xsl:param name="lang" />
|
311 |
+
<xsl:param name="see" />
|
312 |
+
<xsl:param name="space" />
|
313 |
+
<svrl:successful-report test="{$test}" >
|
314 |
+
<xsl:if test=" string-length( $id ) > 0">
|
315 |
+
<axsl:attribute name="id">
|
316 |
+
<xsl:value-of select=" $id " />
|
317 |
+
</axsl:attribute>
|
318 |
+
</xsl:if>
|
319 |
+
<xsl:if test=" string-length( $flag ) > 0">
|
320 |
+
<axsl:attribute name="flag">
|
321 |
+
<xsl:value-of select=" $flag " />
|
322 |
+
</axsl:attribute>
|
323 |
+
</xsl:if>
|
324 |
+
|
325 |
+
<!-- Process rich attributes. -->
|
326 |
+
<xsl:call-template name="richParms">
|
327 |
+
<xsl:with-param name="fpi" select="$fpi"/>
|
328 |
+
<xsl:with-param name="icon" select="$icon"/>
|
329 |
+
<xsl:with-param name="lang" select="$lang"/>
|
330 |
+
<xsl:with-param name="see" select="$see" />
|
331 |
+
<xsl:with-param name="space" select="$space" />
|
332 |
+
</xsl:call-template>
|
333 |
+
<xsl:call-template name='linkableParms'>
|
334 |
+
<xsl:with-param name="role" select="$role" />
|
335 |
+
<xsl:with-param name="subject" select="$subject"/>
|
336 |
+
</xsl:call-template>
|
337 |
+
<xsl:if test=" $generate-paths = 'yes' or $generate-paths = 'true' ">
|
338 |
+
<!-- true/false is the new way -->
|
339 |
+
<axsl:attribute name="location">
|
340 |
+
<axsl:apply-templates select="." mode="schematron-get-full-path"/>
|
341 |
+
</axsl:attribute>
|
342 |
+
</xsl:if>
|
343 |
+
|
344 |
+
<svrl:text>
|
345 |
+
<xsl:apply-templates mode="text" />
|
346 |
+
|
347 |
+
</svrl:text>
|
348 |
+
<xsl:if test="$diagnose = 'yes' or $diagnose='true' ">
|
349 |
+
<!-- true/false is the new way -->
|
350 |
+
<xsl:call-template name="diagnosticsSplit">
|
351 |
+
<xsl:with-param name="str" select="$diagnostics"/>
|
352 |
+
</xsl:call-template>
|
353 |
+
</xsl:if>
|
354 |
+
</svrl:successful-report>
|
355 |
+
</xsl:template>
|
356 |
+
|
357 |
+
|
358 |
+
<!-- Overrides skeleton -->
|
359 |
+
<xsl:template name="process-dir" >
|
360 |
+
<xsl:param name="value" />
|
361 |
+
<xsl:choose>
|
362 |
+
<xsl:when test=" $allow-foreign = 'true'">
|
363 |
+
<xsl:copy-of select="."/>
|
364 |
+
</xsl:when>
|
365 |
+
|
366 |
+
<xsl:otherwise>
|
367 |
+
<!-- We generate too much whitespace rather than risking concatenation -->
|
368 |
+
<axsl:text> </axsl:text>
|
369 |
+
<xsl:apply-templates mode="inline-text"/>
|
370 |
+
<axsl:text> </axsl:text>
|
371 |
+
</xsl:otherwise>
|
372 |
+
</xsl:choose>
|
373 |
+
</xsl:template>
|
374 |
+
|
375 |
+
<xsl:template name="process-diagnostic">
|
376 |
+
<xsl:param name="id"/>
|
377 |
+
<!-- Rich parameters -->
|
378 |
+
<xsl:param name="fpi" />
|
379 |
+
<xsl:param name="icon" />
|
380 |
+
<xsl:param name="lang" />
|
381 |
+
<xsl:param name="see" />
|
382 |
+
<xsl:param name="space" />
|
383 |
+
<svrl:diagnostic-reference diagnostic="{$id}" >
|
384 |
+
|
385 |
+
<xsl:call-template name="richParms">
|
386 |
+
<xsl:with-param name="fpi" select="$fpi"/>
|
387 |
+
<xsl:with-param name="icon" select="$icon"/>
|
388 |
+
<xsl:with-param name="lang" select="$lang"/>
|
389 |
+
<xsl:with-param name="see" select="$see" />
|
390 |
+
<xsl:with-param name="space" select="$space" />
|
391 |
+
</xsl:call-template>
|
392 |
+
<xsl:text>
|
393 |
+
</xsl:text>
|
394 |
+
|
395 |
+
<xsl:apply-templates mode="text"/>
|
396 |
+
|
397 |
+
</svrl:diagnostic-reference>
|
398 |
+
</xsl:template>
|
399 |
+
|
400 |
+
|
401 |
+
<!-- Overrides skeleton -->
|
402 |
+
<xsl:template name="process-emph" >
|
403 |
+
<xsl:param name="class" />
|
404 |
+
<xsl:choose>
|
405 |
+
<xsl:when test=" $allow-foreign = 'true'">
|
406 |
+
<xsl:copy-of select="."/>
|
407 |
+
</xsl:when>
|
408 |
+
<xsl:otherwise>
|
409 |
+
<!-- We generate too much whitespace rather than risking concatenation -->
|
410 |
+
<axsl:text> </axsl:text>
|
411 |
+
<xsl:apply-templates mode="inline-text"/>
|
412 |
+
<axsl:text> </axsl:text>
|
413 |
+
</xsl:otherwise>
|
414 |
+
</xsl:choose>
|
415 |
+
</xsl:template>
|
416 |
+
|
417 |
+
<xsl:template name="process-rule">
|
418 |
+
<xsl:param name="id"/>
|
419 |
+
<xsl:param name="context"/>
|
420 |
+
<xsl:param name="flag"/>
|
421 |
+
<!-- "Linkable" parameters -->
|
422 |
+
<xsl:param name="role"/>
|
423 |
+
<xsl:param name="subject"/>
|
424 |
+
<!-- "Rich" parameters -->
|
425 |
+
<xsl:param name="fpi" />
|
426 |
+
<xsl:param name="icon" />
|
427 |
+
<xsl:param name="lang" />
|
428 |
+
<xsl:param name="see" />
|
429 |
+
<xsl:param name="space" />
|
430 |
+
<xsl:if test=" $generate-fired-rule = 'true'">
|
431 |
+
<svrl:fired-rule context="{$context}" >
|
432 |
+
<!-- Process rich attributes. -->
|
433 |
+
<xsl:call-template name="richParms">
|
434 |
+
<xsl:with-param name="fpi" select="$fpi"/>
|
435 |
+
<xsl:with-param name="icon" select="$icon"/>
|
436 |
+
<xsl:with-param name="lang" select="$lang"/>
|
437 |
+
<xsl:with-param name="see" select="$see" />
|
438 |
+
<xsl:with-param name="space" select="$space" />
|
439 |
+
</xsl:call-template>
|
440 |
+
<xsl:if test=" string( $id )">
|
441 |
+
<xsl:attribute name="id">
|
442 |
+
<xsl:value-of select=" $id " />
|
443 |
+
</xsl:attribute>
|
444 |
+
</xsl:if>
|
445 |
+
<xsl:if test=" string-length( $role ) > 0">
|
446 |
+
<xsl:attribute name="role">
|
447 |
+
<xsl:value-of select=" $role " />
|
448 |
+
</xsl:attribute>
|
449 |
+
</xsl:if>
|
450 |
+
</svrl:fired-rule>
|
451 |
+
</xsl:if>
|
452 |
+
</xsl:template>
|
453 |
+
|
454 |
+
<xsl:template name="process-ns">
|
455 |
+
<xsl:param name="prefix"/>
|
456 |
+
<xsl:param name="uri"/>
|
457 |
+
<svrl:ns-prefix-in-attribute-values uri="{$uri}" prefix="{$prefix}" />
|
458 |
+
</xsl:template>
|
459 |
+
|
460 |
+
<xsl:template name="process-p">
|
461 |
+
<xsl:param name="icon"/>
|
462 |
+
<xsl:param name="class"/>
|
463 |
+
<xsl:param name="id"/>
|
464 |
+
<xsl:param name="lang"/>
|
465 |
+
|
466 |
+
<svrl:text>
|
467 |
+
<xsl:apply-templates mode="text"/>
|
468 |
+
</svrl:text>
|
469 |
+
</xsl:template>
|
470 |
+
|
471 |
+
<xsl:template name="process-pattern">
|
472 |
+
<xsl:param name="name"/>
|
473 |
+
<xsl:param name="id"/>
|
474 |
+
<xsl:param name="is-a"/>
|
475 |
+
|
476 |
+
<!-- "Rich" parameters -->
|
477 |
+
<xsl:param name="fpi" />
|
478 |
+
<xsl:param name="icon" />
|
479 |
+
<xsl:param name="lang" />
|
480 |
+
<xsl:param name="see" />
|
481 |
+
<xsl:param name="space" />
|
482 |
+
<svrl:active-pattern >
|
483 |
+
<xsl:if test=" string( $id )">
|
484 |
+
<axsl:attribute name="id">
|
485 |
+
<xsl:value-of select=" $id " />
|
486 |
+
</axsl:attribute>
|
487 |
+
</xsl:if>
|
488 |
+
<xsl:if test=" string( $name )">
|
489 |
+
<axsl:attribute name="name">
|
490 |
+
<xsl:value-of select=" $name " />
|
491 |
+
</axsl:attribute>
|
492 |
+
</xsl:if>
|
493 |
+
|
494 |
+
<xsl:call-template name='richParms'>
|
495 |
+
<xsl:with-param name="fpi" select="$fpi"/>
|
496 |
+
<xsl:with-param name="icon" select="$icon"/>
|
497 |
+
<xsl:with-param name="lang" select="$lang"/>
|
498 |
+
<xsl:with-param name="see" select="$see" />
|
499 |
+
<xsl:with-param name="space" select="$space" />
|
500 |
+
</xsl:call-template>
|
501 |
+
|
502 |
+
<!-- ?? report that this screws up iso:title processing -->
|
503 |
+
<xsl:apply-templates mode="do-pattern-p"/>
|
504 |
+
<!-- ?? Seems that this apply-templates is never triggered DP -->
|
505 |
+
<axsl:apply-templates />
|
506 |
+
</svrl:active-pattern>
|
507 |
+
</xsl:template>
|
508 |
+
|
509 |
+
<!-- Overrides skeleton -->
|
510 |
+
<xsl:template name="process-message" >
|
511 |
+
<xsl:param name="pattern"/>
|
512 |
+
<xsl:param name="role"/>
|
513 |
+
</xsl:template>
|
514 |
+
|
515 |
+
|
516 |
+
<!-- Overrides skeleton -->
|
517 |
+
<xsl:template name="process-span" >
|
518 |
+
<xsl:param name="class" />
|
519 |
+
<xsl:choose>
|
520 |
+
<xsl:when test=" $allow-foreign = 'true'">
|
521 |
+
<xsl:copy-of select="."/>
|
522 |
+
</xsl:when>
|
523 |
+
<xsl:otherwise>
|
524 |
+
<!-- We generate too much whitespace rather than risking concatenation -->
|
525 |
+
<axsl:text> </axsl:text>
|
526 |
+
<xsl:apply-templates mode="inline-text"/>
|
527 |
+
<axsl:text> </axsl:text>
|
528 |
+
</xsl:otherwise>
|
529 |
+
</xsl:choose>
|
530 |
+
</xsl:template>
|
531 |
+
|
532 |
+
<!-- =========================================================================== -->
|
533 |
+
<!-- processing rich parameters. -->
|
534 |
+
<xsl:template name='richParms'>
|
535 |
+
<!-- "Rich" parameters -->
|
536 |
+
<xsl:param name="fpi" />
|
537 |
+
<xsl:param name="icon" />
|
538 |
+
<xsl:param name="lang" />
|
539 |
+
<xsl:param name="see" />
|
540 |
+
<xsl:param name="space" />
|
541 |
+
<!-- Process rich attributes. -->
|
542 |
+
<xsl:if test=" $allow-foreign = 'true'">
|
543 |
+
<xsl:if test="string($fpi)">
|
544 |
+
<axsl:attribute name="fpi">
|
545 |
+
<xsl:value-of select="$fpi"/>
|
546 |
+
</axsl:attribute>
|
547 |
+
</xsl:if>
|
548 |
+
<xsl:if test="string($icon)">
|
549 |
+
<axsl:attribute name="icon">
|
550 |
+
<xsl:value-of select="$icon"/>
|
551 |
+
</axsl:attribute>
|
552 |
+
</xsl:if>
|
553 |
+
<xsl:if test="string($see)">
|
554 |
+
<axsl:attribute name="see">
|
555 |
+
<xsl:value-of select="$see"/>
|
556 |
+
</axsl:attribute>
|
557 |
+
</xsl:if>
|
558 |
+
</xsl:if>
|
559 |
+
<xsl:if test="string($space)">
|
560 |
+
<axsl:attribute name="xml:space">
|
561 |
+
<xsl:value-of select="$space"/>
|
562 |
+
</axsl:attribute>
|
563 |
+
</xsl:if>
|
564 |
+
<xsl:if test="string($lang)">
|
565 |
+
<axsl:attribute name="xml:lang">
|
566 |
+
<xsl:value-of select="$lang"/>
|
567 |
+
</axsl:attribute>
|
568 |
+
</xsl:if>
|
569 |
+
</xsl:template>
|
570 |
+
|
571 |
+
<!-- processing linkable parameters. -->
|
572 |
+
<xsl:template name='linkableParms'>
|
573 |
+
<xsl:param name="role"/>
|
574 |
+
<xsl:param name="subject"/>
|
575 |
+
|
576 |
+
<!-- ISO SVRL has a role attribute to match the Schematron role attribute -->
|
577 |
+
<xsl:if test=" string($role )">
|
578 |
+
<axsl:attribute name="role">
|
579 |
+
<xsl:value-of select=" $role " />
|
580 |
+
</axsl:attribute>
|
581 |
+
</xsl:if>
|
582 |
+
<!-- ISO SVRL does not have a subject attribute to match the Schematron subject attribute.
|
583 |
+
Instead, the Schematron subject attribute is folded into the location attribute -->
|
584 |
+
</xsl:template>
|
585 |
+
|
586 |
+
|
587 |
+
</xsl:stylesheet>
|
588 |
+
|
llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/readme.txt
ADDED
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
ISO SCHEMATRON 2010
|
2 |
+
|
3 |
+
XSLT implementation by Rick Jelliffe with assistance from members of Schematron-love-in maillist.
|
4 |
+
|
5 |
+
2010-04-21
|
6 |
+
|
7 |
+
Two distributions are available. One is for XSLT1 engines.
|
8 |
+
The other is for XSLT2 engines, such as SAXON 9.
|
9 |
+
|
10 |
+
|
11 |
+
This version of Schematron splits the process into a pipeline of several different XSLT stages.
|
12 |
+
|
13 |
+
1) First, preprocess your Schematron schema with iso_dsdl_include.xsl.
|
14 |
+
This is a macro processor to assemble the schema from various parts.
|
15 |
+
If your schema is not in separate parts, you can skip this stage.
|
16 |
+
This stage also generates error messages for some common XPath syntax problems.
|
17 |
+
|
18 |
+
2) Second, preprocess the output from stage 1 with iso_abstract_expand.xsl.
|
19 |
+
This is a macro processor to convert abstract patterns to real patterns.
|
20 |
+
If your schema does not use abstract patterns, you can skip this
|
21 |
+
stage.
|
22 |
+
|
23 |
+
3) Third, compile the Schematron schema into an XSLT script.
|
24 |
+
This will typically use iso_svrl_for_xslt1.xsl or iso_svrl_for_xslt2.xsl
|
25 |
+
(which in turn invoke iso_schematron_skeleton_for_xslt1.xsl or iso_schematron_skeleton_for_saxon.xsl)
|
26 |
+
However, other "meta-stylesheets" are also in common use; the principle of operation is the same.
|
27 |
+
If your schema uses Schematron phases, supply these as command line/invocation parameters
|
28 |
+
to this process.
|
29 |
+
|
30 |
+
4) Fourth, run the script generated by stage 3 against the document being validated.
|
31 |
+
If you are using the SVRL script, then the output of validation will be an XML document.
|
32 |
+
If your schema uses Schematron parameters, supply these as command line/invocation parameters
|
33 |
+
to this process.
|
34 |
+
|
35 |
+
|
36 |
+
The XSLT2 distribution also features several next generation features,
|
37 |
+
such as validating multiple documents. See the source code for details.
|
38 |
+
|
39 |
+
Schematron assertions can be written in any language, of course; the file
|
40 |
+
sch-messages-en.xhtml contains the diagnostics messages from the XSLT2 skeleton
|
41 |
+
in English, and this can be used as template to localize the skeleton's
|
42 |
+
error messages. Note that typically programming errors in Schematron are XPath
|
43 |
+
errors, which requires localized messages from the XSLT engine.
|
44 |
+
|
45 |
+
ANT
|
46 |
+
---
|
47 |
+
To give an example of how to process a document, here is a sample ANT task.
|
48 |
+
|
49 |
+
<target name="schematron-compile-test" >
|
50 |
+
|
51 |
+
<!-- expand inclusions -->
|
52 |
+
<xslt basedir="test/schematron"
|
53 |
+
style="iso_dsdl_include.xsl" in="test.sch" out="test1.sch">
|
54 |
+
<classpath>
|
55 |
+
<pathelement location="${lib.dir}/saxon9.jar"/>
|
56 |
+
</classpath>
|
57 |
+
</xslt>
|
58 |
+
|
59 |
+
<!-- expand abstract patterns -->
|
60 |
+
<xslt basedir="test/schematron"
|
61 |
+
style="iso_abstract_expand.xsl" in="test1.sch" out="test2.sch">
|
62 |
+
<classpath>
|
63 |
+
<pathelement location="${lib.dir}/saxon9.jar"/>
|
64 |
+
</classpath>
|
65 |
+
</xslt>
|
66 |
+
|
67 |
+
|
68 |
+
|
69 |
+
<!-- compile it -->
|
70 |
+
<xslt basedir="test/schematron"
|
71 |
+
style="iso_svrl_for_xslt2.xsl" in="test2.sch" out="test.xsl">
|
72 |
+
<classpath>
|
73 |
+
<pathelement location="${lib.dir}/saxon9.jar"/>
|
74 |
+
</classpath>
|
75 |
+
</xslt>
|
76 |
+
|
77 |
+
<!-- validate -->
|
78 |
+
<xslt basedir="test/schematron"
|
79 |
+
style="test.xsl" in="instance.xml" out="instance.svrlt">
|
80 |
+
<classpath>
|
81 |
+
<pathelement location="${lib.dir}/saxon9.jar"/>
|
82 |
+
</classpath>
|
83 |
+
</xslt>
|
84 |
+
</target>
|
llmeval-env/lib/python3.10/site-packages/lxml/iterparse.pxi
ADDED
@@ -0,0 +1,438 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# iterparse -- event-driven parsing
|
2 |
+
|
3 |
+
DEF __ITERPARSE_CHUNK_SIZE = 32768
|
4 |
+
|
5 |
+
cdef class iterparse:
|
6 |
+
"""iterparse(self, source, events=("end",), tag=None, \
|
7 |
+
attribute_defaults=False, dtd_validation=False, \
|
8 |
+
load_dtd=False, no_network=True, remove_blank_text=False, \
|
9 |
+
remove_comments=False, remove_pis=False, encoding=None, \
|
10 |
+
html=False, recover=None, huge_tree=False, schema=None)
|
11 |
+
|
12 |
+
Incremental parser.
|
13 |
+
|
14 |
+
Parses XML into a tree and generates tuples (event, element) in a
|
15 |
+
SAX-like fashion. ``event`` is any of 'start', 'end', 'start-ns',
|
16 |
+
'end-ns'.
|
17 |
+
|
18 |
+
For 'start' and 'end', ``element`` is the Element that the parser just
|
19 |
+
found opening or closing. For 'start-ns', it is a tuple (prefix, URI) of
|
20 |
+
a new namespace declaration. For 'end-ns', it is simply None. Note that
|
21 |
+
all start and end events are guaranteed to be properly nested.
|
22 |
+
|
23 |
+
The keyword argument ``events`` specifies a sequence of event type names
|
24 |
+
that should be generated. By default, only 'end' events will be
|
25 |
+
generated.
|
26 |
+
|
27 |
+
The additional ``tag`` argument restricts the 'start' and 'end' events to
|
28 |
+
those elements that match the given tag. The ``tag`` argument can also be
|
29 |
+
a sequence of tags to allow matching more than one tag. By default,
|
30 |
+
events are generated for all elements. Note that the 'start-ns' and
|
31 |
+
'end-ns' events are not impacted by this restriction.
|
32 |
+
|
33 |
+
The other keyword arguments in the constructor are mainly based on the
|
34 |
+
libxml2 parser configuration. A DTD will also be loaded if validation or
|
35 |
+
attribute default values are requested.
|
36 |
+
|
37 |
+
Available boolean keyword arguments:
|
38 |
+
- attribute_defaults: read default attributes from DTD
|
39 |
+
- dtd_validation: validate (if DTD is available)
|
40 |
+
- load_dtd: use DTD for parsing
|
41 |
+
- no_network: prevent network access for related files
|
42 |
+
- remove_blank_text: discard blank text nodes
|
43 |
+
- remove_comments: discard comments
|
44 |
+
- remove_pis: discard processing instructions
|
45 |
+
- strip_cdata: replace CDATA sections by normal text content (default: True)
|
46 |
+
- compact: safe memory for short text content (default: True)
|
47 |
+
- resolve_entities: replace entities by their text value (default: True)
|
48 |
+
- huge_tree: disable security restrictions and support very deep trees
|
49 |
+
and very long text content (only affects libxml2 2.7+)
|
50 |
+
- html: parse input as HTML (default: XML)
|
51 |
+
- recover: try hard to parse through broken input (default: True for HTML,
|
52 |
+
False otherwise)
|
53 |
+
|
54 |
+
Other keyword arguments:
|
55 |
+
- encoding: override the document encoding
|
56 |
+
- schema: an XMLSchema to validate against
|
57 |
+
"""
|
58 |
+
cdef _FeedParser _parser
|
59 |
+
cdef object _tag
|
60 |
+
cdef object _events
|
61 |
+
cdef readonly object root
|
62 |
+
cdef object _source
|
63 |
+
cdef object _filename
|
64 |
+
cdef object _error
|
65 |
+
cdef bint _close_source_after_read
|
66 |
+
|
67 |
+
def __init__(self, source, events=("end",), *, tag=None,
|
68 |
+
attribute_defaults=False, dtd_validation=False,
|
69 |
+
load_dtd=False, no_network=True, remove_blank_text=False,
|
70 |
+
compact=True, resolve_entities=True, remove_comments=False,
|
71 |
+
remove_pis=False, strip_cdata=True, encoding=None,
|
72 |
+
html=False, recover=None, huge_tree=False, collect_ids=True,
|
73 |
+
XMLSchema schema=None):
|
74 |
+
if not hasattr(source, 'read'):
|
75 |
+
source = _getFSPathOrObject(source)
|
76 |
+
self._filename = source
|
77 |
+
self._source = open(source, 'rb')
|
78 |
+
self._close_source_after_read = True
|
79 |
+
else:
|
80 |
+
self._filename = _getFilenameForFile(source)
|
81 |
+
self._source = source
|
82 |
+
self._close_source_after_read = False
|
83 |
+
|
84 |
+
if recover is None:
|
85 |
+
recover = html
|
86 |
+
|
87 |
+
if html:
|
88 |
+
# make sure we're not looking for namespaces
|
89 |
+
events = [event for event in events
|
90 |
+
if event not in ('start-ns', 'end-ns')]
|
91 |
+
parser = HTMLPullParser(
|
92 |
+
events,
|
93 |
+
tag=tag,
|
94 |
+
recover=recover,
|
95 |
+
base_url=self._filename,
|
96 |
+
encoding=encoding,
|
97 |
+
remove_blank_text=remove_blank_text,
|
98 |
+
remove_comments=remove_comments,
|
99 |
+
remove_pis=remove_pis,
|
100 |
+
strip_cdata=strip_cdata,
|
101 |
+
no_network=no_network,
|
102 |
+
target=None, # TODO
|
103 |
+
schema=schema,
|
104 |
+
compact=compact)
|
105 |
+
else:
|
106 |
+
parser = XMLPullParser(
|
107 |
+
events,
|
108 |
+
tag=tag,
|
109 |
+
recover=recover,
|
110 |
+
base_url=self._filename,
|
111 |
+
encoding=encoding,
|
112 |
+
attribute_defaults=attribute_defaults,
|
113 |
+
dtd_validation=dtd_validation,
|
114 |
+
load_dtd=load_dtd,
|
115 |
+
no_network=no_network,
|
116 |
+
schema=schema,
|
117 |
+
huge_tree=huge_tree,
|
118 |
+
remove_blank_text=remove_blank_text,
|
119 |
+
resolve_entities=resolve_entities,
|
120 |
+
remove_comments=remove_comments,
|
121 |
+
remove_pis=remove_pis,
|
122 |
+
strip_cdata=strip_cdata,
|
123 |
+
collect_ids=True,
|
124 |
+
target=None, # TODO
|
125 |
+
compact=compact)
|
126 |
+
|
127 |
+
self._events = parser.read_events()
|
128 |
+
self._parser = parser
|
129 |
+
|
130 |
+
@property
|
131 |
+
def error_log(self):
|
132 |
+
"""The error log of the last (or current) parser run.
|
133 |
+
"""
|
134 |
+
return self._parser.feed_error_log
|
135 |
+
|
136 |
+
@property
|
137 |
+
def resolvers(self):
|
138 |
+
"""The custom resolver registry of the last (or current) parser run.
|
139 |
+
"""
|
140 |
+
return self._parser.resolvers
|
141 |
+
|
142 |
+
@property
|
143 |
+
def version(self):
|
144 |
+
"""The version of the underlying XML parser."""
|
145 |
+
return self._parser.version
|
146 |
+
|
147 |
+
def set_element_class_lookup(self, ElementClassLookup lookup = None):
|
148 |
+
"""set_element_class_lookup(self, lookup = None)
|
149 |
+
|
150 |
+
Set a lookup scheme for element classes generated from this parser.
|
151 |
+
|
152 |
+
Reset it by passing None or nothing.
|
153 |
+
"""
|
154 |
+
self._parser.set_element_class_lookup(lookup)
|
155 |
+
|
156 |
+
def makeelement(self, _tag, attrib=None, nsmap=None, **_extra):
|
157 |
+
"""makeelement(self, _tag, attrib=None, nsmap=None, **_extra)
|
158 |
+
|
159 |
+
Creates a new element associated with this parser.
|
160 |
+
"""
|
161 |
+
self._parser.makeelement(
|
162 |
+
_tag, attrib=None, nsmap=None, **_extra)
|
163 |
+
|
164 |
+
@cython.final
|
165 |
+
cdef _close_source(self):
|
166 |
+
if self._source is None:
|
167 |
+
return
|
168 |
+
if not self._close_source_after_read:
|
169 |
+
self._source = None
|
170 |
+
return
|
171 |
+
try:
|
172 |
+
close = self._source.close
|
173 |
+
except AttributeError:
|
174 |
+
close = None
|
175 |
+
finally:
|
176 |
+
self._source = None
|
177 |
+
if close is not None:
|
178 |
+
close()
|
179 |
+
|
180 |
+
def __iter__(self):
|
181 |
+
return self
|
182 |
+
|
183 |
+
def __next__(self):
|
184 |
+
try:
|
185 |
+
return next(self._events)
|
186 |
+
except StopIteration:
|
187 |
+
pass
|
188 |
+
context = <_SaxParserContext>self._parser._getPushParserContext()
|
189 |
+
if self._source is not None:
|
190 |
+
done = False
|
191 |
+
while not done:
|
192 |
+
try:
|
193 |
+
done = self._read_more_events(context)
|
194 |
+
return next(self._events)
|
195 |
+
except StopIteration:
|
196 |
+
pass # no events yet
|
197 |
+
except Exception as e:
|
198 |
+
self._error = e
|
199 |
+
self._close_source()
|
200 |
+
try:
|
201 |
+
return next(self._events)
|
202 |
+
except StopIteration:
|
203 |
+
break
|
204 |
+
# nothing left to read or return
|
205 |
+
if self._error is not None:
|
206 |
+
error = self._error
|
207 |
+
self._error = None
|
208 |
+
raise error
|
209 |
+
if (context._validator is not None
|
210 |
+
and not context._validator.isvalid()):
|
211 |
+
_raiseParseError(context._c_ctxt, self._filename,
|
212 |
+
context._error_log)
|
213 |
+
# no errors => all done
|
214 |
+
raise StopIteration
|
215 |
+
|
216 |
+
@cython.final
|
217 |
+
cdef bint _read_more_events(self, _SaxParserContext context) except -123:
|
218 |
+
data = self._source.read(__ITERPARSE_CHUNK_SIZE)
|
219 |
+
if not isinstance(data, bytes):
|
220 |
+
self._close_source()
|
221 |
+
raise TypeError("reading file objects must return bytes objects")
|
222 |
+
if not data:
|
223 |
+
try:
|
224 |
+
self.root = self._parser.close()
|
225 |
+
finally:
|
226 |
+
self._close_source()
|
227 |
+
return True
|
228 |
+
self._parser.feed(data)
|
229 |
+
return False
|
230 |
+
|
231 |
+
|
232 |
+
cdef enum _IterwalkSkipStates:
|
233 |
+
IWSKIP_NEXT_IS_START
|
234 |
+
IWSKIP_SKIP_NEXT
|
235 |
+
IWSKIP_CAN_SKIP
|
236 |
+
IWSKIP_CANNOT_SKIP
|
237 |
+
|
238 |
+
|
239 |
+
cdef class iterwalk:
|
240 |
+
"""iterwalk(self, element_or_tree, events=("end",), tag=None)
|
241 |
+
|
242 |
+
A tree walker that generates events from an existing tree as if it
|
243 |
+
was parsing XML data with ``iterparse()``.
|
244 |
+
|
245 |
+
Just as for ``iterparse()``, the ``tag`` argument can be a single tag or a
|
246 |
+
sequence of tags.
|
247 |
+
|
248 |
+
After receiving a 'start' or 'start-ns' event, the children and
|
249 |
+
descendants of the current element can be excluded from iteration
|
250 |
+
by calling the ``skip_subtree()`` method.
|
251 |
+
"""
|
252 |
+
cdef _MultiTagMatcher _matcher
|
253 |
+
cdef list _node_stack
|
254 |
+
cdef list _events
|
255 |
+
cdef object _pop_event
|
256 |
+
cdef object _include_siblings
|
257 |
+
cdef int _index
|
258 |
+
cdef int _event_filter
|
259 |
+
cdef _IterwalkSkipStates _skip_state
|
260 |
+
|
261 |
+
def __init__(self, element_or_tree, events=("end",), tag=None):
|
262 |
+
cdef _Element root
|
263 |
+
cdef int ns_count
|
264 |
+
root = _rootNodeOrRaise(element_or_tree)
|
265 |
+
self._event_filter = _buildParseEventFilter(events)
|
266 |
+
if tag is None or tag == '*':
|
267 |
+
self._matcher = None
|
268 |
+
else:
|
269 |
+
self._matcher = _MultiTagMatcher.__new__(_MultiTagMatcher, tag)
|
270 |
+
self._node_stack = []
|
271 |
+
self._events = []
|
272 |
+
self._pop_event = self._events.pop
|
273 |
+
self._skip_state = IWSKIP_CANNOT_SKIP # ignore all skip requests by default
|
274 |
+
|
275 |
+
if self._event_filter:
|
276 |
+
self._index = 0
|
277 |
+
if self._matcher is not None and self._event_filter & PARSE_EVENT_FILTER_START:
|
278 |
+
self._matcher.cacheTags(root._doc)
|
279 |
+
|
280 |
+
# When processing an ElementTree, add events for the preceding comments/PIs.
|
281 |
+
if self._event_filter & (PARSE_EVENT_FILTER_COMMENT | PARSE_EVENT_FILTER_PI):
|
282 |
+
if isinstance(element_or_tree, _ElementTree):
|
283 |
+
self._include_siblings = root
|
284 |
+
for elem in list(root.itersiblings(preceding=True))[::-1]:
|
285 |
+
if self._event_filter & PARSE_EVENT_FILTER_COMMENT and elem.tag is Comment:
|
286 |
+
self._events.append(('comment', elem))
|
287 |
+
elif self._event_filter & PARSE_EVENT_FILTER_PI and elem.tag is PI:
|
288 |
+
self._events.append(('pi', elem))
|
289 |
+
|
290 |
+
ns_count = self._start_node(root)
|
291 |
+
self._node_stack.append( (root, ns_count) )
|
292 |
+
else:
|
293 |
+
self._index = -1
|
294 |
+
|
295 |
+
def __iter__(self):
|
296 |
+
return self
|
297 |
+
|
298 |
+
def __next__(self):
|
299 |
+
cdef xmlNode* c_child
|
300 |
+
cdef _Element node
|
301 |
+
cdef _Element next_node
|
302 |
+
cdef int ns_count = 0
|
303 |
+
if self._events:
|
304 |
+
return self._next_event()
|
305 |
+
if self._matcher is not None and self._index >= 0:
|
306 |
+
node = self._node_stack[self._index][0]
|
307 |
+
self._matcher.cacheTags(node._doc)
|
308 |
+
|
309 |
+
# find next node
|
310 |
+
while self._index >= 0:
|
311 |
+
node = self._node_stack[self._index][0]
|
312 |
+
|
313 |
+
if self._skip_state == IWSKIP_SKIP_NEXT:
|
314 |
+
c_child = NULL
|
315 |
+
else:
|
316 |
+
c_child = self._process_non_elements(
|
317 |
+
node._doc, _findChildForwards(node._c_node, 0))
|
318 |
+
self._skip_state = IWSKIP_CANNOT_SKIP
|
319 |
+
|
320 |
+
while c_child is NULL:
|
321 |
+
# back off through parents
|
322 |
+
self._index -= 1
|
323 |
+
node = self._end_node()
|
324 |
+
if self._index < 0:
|
325 |
+
break
|
326 |
+
c_child = self._process_non_elements(
|
327 |
+
node._doc, _nextElement(node._c_node))
|
328 |
+
|
329 |
+
if c_child is not NULL:
|
330 |
+
next_node = _elementFactory(node._doc, c_child)
|
331 |
+
if self._event_filter & (PARSE_EVENT_FILTER_START |
|
332 |
+
PARSE_EVENT_FILTER_START_NS):
|
333 |
+
ns_count = self._start_node(next_node)
|
334 |
+
elif self._event_filter & PARSE_EVENT_FILTER_END_NS:
|
335 |
+
ns_count = _countNsDefs(next_node._c_node)
|
336 |
+
self._node_stack.append( (next_node, ns_count) )
|
337 |
+
self._index += 1
|
338 |
+
if self._events:
|
339 |
+
return self._next_event()
|
340 |
+
|
341 |
+
if self._include_siblings is not None:
|
342 |
+
node, self._include_siblings = self._include_siblings, None
|
343 |
+
self._process_non_elements(node._doc, _nextElement(node._c_node))
|
344 |
+
if self._events:
|
345 |
+
return self._next_event()
|
346 |
+
|
347 |
+
raise StopIteration
|
348 |
+
|
349 |
+
@cython.final
|
350 |
+
cdef xmlNode* _process_non_elements(self, _Document doc, xmlNode* c_node):
|
351 |
+
while c_node is not NULL and c_node.type != tree.XML_ELEMENT_NODE:
|
352 |
+
if c_node.type == tree.XML_COMMENT_NODE:
|
353 |
+
if self._event_filter & PARSE_EVENT_FILTER_COMMENT:
|
354 |
+
self._events.append(
|
355 |
+
("comment", _elementFactory(doc, c_node)))
|
356 |
+
c_node = _nextElement(c_node)
|
357 |
+
elif c_node.type == tree.XML_PI_NODE:
|
358 |
+
if self._event_filter & PARSE_EVENT_FILTER_PI:
|
359 |
+
self._events.append(
|
360 |
+
("pi", _elementFactory(doc, c_node)))
|
361 |
+
c_node = _nextElement(c_node)
|
362 |
+
else:
|
363 |
+
break
|
364 |
+
return c_node
|
365 |
+
|
366 |
+
@cython.final
|
367 |
+
cdef _next_event(self):
|
368 |
+
if self._skip_state == IWSKIP_NEXT_IS_START:
|
369 |
+
if self._events[0][0] in ('start', 'start-ns'):
|
370 |
+
self._skip_state = IWSKIP_CAN_SKIP
|
371 |
+
return self._pop_event(0)
|
372 |
+
|
373 |
+
def skip_subtree(self):
|
374 |
+
"""Prevent descending into the current subtree.
|
375 |
+
Instead, the next returned event will be the 'end' event of the current element
|
376 |
+
(if included), ignoring any children or descendants.
|
377 |
+
|
378 |
+
This has no effect right after an 'end' or 'end-ns' event.
|
379 |
+
"""
|
380 |
+
if self._skip_state == IWSKIP_CAN_SKIP:
|
381 |
+
self._skip_state = IWSKIP_SKIP_NEXT
|
382 |
+
|
383 |
+
@cython.final
|
384 |
+
cdef int _start_node(self, _Element node) except -1:
|
385 |
+
cdef int ns_count
|
386 |
+
if self._event_filter & PARSE_EVENT_FILTER_START_NS:
|
387 |
+
ns_count = _appendStartNsEvents(node._c_node, self._events)
|
388 |
+
if self._events:
|
389 |
+
self._skip_state = IWSKIP_NEXT_IS_START
|
390 |
+
elif self._event_filter & PARSE_EVENT_FILTER_END_NS:
|
391 |
+
ns_count = _countNsDefs(node._c_node)
|
392 |
+
else:
|
393 |
+
ns_count = 0
|
394 |
+
if self._event_filter & PARSE_EVENT_FILTER_START:
|
395 |
+
if self._matcher is None or self._matcher.matches(node._c_node):
|
396 |
+
self._events.append( ("start", node) )
|
397 |
+
self._skip_state = IWSKIP_NEXT_IS_START
|
398 |
+
return ns_count
|
399 |
+
|
400 |
+
@cython.final
|
401 |
+
cdef _Element _end_node(self):
|
402 |
+
cdef _Element node
|
403 |
+
cdef int i, ns_count
|
404 |
+
node, ns_count = self._node_stack.pop()
|
405 |
+
if self._event_filter & PARSE_EVENT_FILTER_END:
|
406 |
+
if self._matcher is None or self._matcher.matches(node._c_node):
|
407 |
+
self._events.append( ("end", node) )
|
408 |
+
if self._event_filter & PARSE_EVENT_FILTER_END_NS and ns_count:
|
409 |
+
event = ("end-ns", None)
|
410 |
+
for i in range(ns_count):
|
411 |
+
self._events.append(event)
|
412 |
+
return node
|
413 |
+
|
414 |
+
|
415 |
+
cdef int _countNsDefs(xmlNode* c_node) noexcept:
|
416 |
+
cdef xmlNs* c_ns
|
417 |
+
cdef int count
|
418 |
+
count = 0
|
419 |
+
c_ns = c_node.nsDef
|
420 |
+
while c_ns is not NULL:
|
421 |
+
count += (c_ns.href is not NULL)
|
422 |
+
c_ns = c_ns.next
|
423 |
+
return count
|
424 |
+
|
425 |
+
|
426 |
+
cdef int _appendStartNsEvents(xmlNode* c_node, list event_list) except -1:
|
427 |
+
cdef xmlNs* c_ns
|
428 |
+
cdef int count
|
429 |
+
count = 0
|
430 |
+
c_ns = c_node.nsDef
|
431 |
+
while c_ns is not NULL:
|
432 |
+
if c_ns.href:
|
433 |
+
ns_tuple = (funicodeOrEmpty(c_ns.prefix),
|
434 |
+
funicode(c_ns.href))
|
435 |
+
event_list.append( ("start-ns", ns_tuple) )
|
436 |
+
count += 1
|
437 |
+
c_ns = c_ns.next
|
438 |
+
return count
|
llmeval-env/lib/python3.10/site-packages/lxml/lxml.etree_api.h
ADDED
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/* Generated by Cython 3.0.10 */
|
2 |
+
|
3 |
+
#ifndef __PYX_HAVE_API__lxml__etree
|
4 |
+
#define __PYX_HAVE_API__lxml__etree
|
5 |
+
#ifdef __MINGW64__
|
6 |
+
#define MS_WIN64
|
7 |
+
#endif
|
8 |
+
#include "Python.h"
|
9 |
+
#include "lxml.etree.h"
|
10 |
+
|
11 |
+
static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_deepcopyNodeToDocument)(struct LxmlDocument *, xmlNode *) = 0;
|
12 |
+
#define deepcopyNodeToDocument __pyx_api_f_4lxml_5etree_deepcopyNodeToDocument
|
13 |
+
static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_elementTreeFactory)(struct LxmlElement *) = 0;
|
14 |
+
#define elementTreeFactory __pyx_api_f_4lxml_5etree_elementTreeFactory
|
15 |
+
static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_newElementTree)(struct LxmlElement *, PyObject *) = 0;
|
16 |
+
#define newElementTree __pyx_api_f_4lxml_5etree_newElementTree
|
17 |
+
static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_adoptExternalDocument)(xmlDoc *, PyObject *, int) = 0;
|
18 |
+
#define adoptExternalDocument __pyx_api_f_4lxml_5etree_adoptExternalDocument
|
19 |
+
static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_elementFactory)(struct LxmlDocument *, xmlNode *) = 0;
|
20 |
+
#define elementFactory __pyx_api_f_4lxml_5etree_elementFactory
|
21 |
+
static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_makeElement)(PyObject *, struct LxmlDocument *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *) = 0;
|
22 |
+
#define makeElement __pyx_api_f_4lxml_5etree_makeElement
|
23 |
+
static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_makeSubElement)(struct LxmlElement *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *) = 0;
|
24 |
+
#define makeSubElement __pyx_api_f_4lxml_5etree_makeSubElement
|
25 |
+
static void (*__pyx_api_f_4lxml_5etree_setElementClassLookupFunction)(_element_class_lookup_function, PyObject *) = 0;
|
26 |
+
#define setElementClassLookupFunction __pyx_api_f_4lxml_5etree_setElementClassLookupFunction
|
27 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_lookupDefaultElementClass)(PyObject *, PyObject *, xmlNode *) = 0;
|
28 |
+
#define lookupDefaultElementClass __pyx_api_f_4lxml_5etree_lookupDefaultElementClass
|
29 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_lookupNamespaceElementClass)(PyObject *, PyObject *, xmlNode *) = 0;
|
30 |
+
#define lookupNamespaceElementClass __pyx_api_f_4lxml_5etree_lookupNamespaceElementClass
|
31 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_callLookupFallback)(struct LxmlFallbackElementClassLookup *, struct LxmlDocument *, xmlNode *) = 0;
|
32 |
+
#define callLookupFallback __pyx_api_f_4lxml_5etree_callLookupFallback
|
33 |
+
static int (*__pyx_api_f_4lxml_5etree_tagMatches)(xmlNode *, const xmlChar *, const xmlChar *) = 0;
|
34 |
+
#define tagMatches __pyx_api_f_4lxml_5etree_tagMatches
|
35 |
+
static struct LxmlDocument *(*__pyx_api_f_4lxml_5etree_documentOrRaise)(PyObject *) = 0;
|
36 |
+
#define documentOrRaise __pyx_api_f_4lxml_5etree_documentOrRaise
|
37 |
+
static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_rootNodeOrRaise)(PyObject *) = 0;
|
38 |
+
#define rootNodeOrRaise __pyx_api_f_4lxml_5etree_rootNodeOrRaise
|
39 |
+
static int (*__pyx_api_f_4lxml_5etree_hasText)(xmlNode *) = 0;
|
40 |
+
#define hasText __pyx_api_f_4lxml_5etree_hasText
|
41 |
+
static int (*__pyx_api_f_4lxml_5etree_hasTail)(xmlNode *) = 0;
|
42 |
+
#define hasTail __pyx_api_f_4lxml_5etree_hasTail
|
43 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_textOf)(xmlNode *) = 0;
|
44 |
+
#define textOf __pyx_api_f_4lxml_5etree_textOf
|
45 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_tailOf)(xmlNode *) = 0;
|
46 |
+
#define tailOf __pyx_api_f_4lxml_5etree_tailOf
|
47 |
+
static int (*__pyx_api_f_4lxml_5etree_setNodeText)(xmlNode *, PyObject *) = 0;
|
48 |
+
#define setNodeText __pyx_api_f_4lxml_5etree_setNodeText
|
49 |
+
static int (*__pyx_api_f_4lxml_5etree_setTailText)(xmlNode *, PyObject *) = 0;
|
50 |
+
#define setTailText __pyx_api_f_4lxml_5etree_setTailText
|
51 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_attributeValue)(xmlNode *, xmlAttr *) = 0;
|
52 |
+
#define attributeValue __pyx_api_f_4lxml_5etree_attributeValue
|
53 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_attributeValueFromNsName)(xmlNode *, const xmlChar *, const xmlChar *) = 0;
|
54 |
+
#define attributeValueFromNsName __pyx_api_f_4lxml_5etree_attributeValueFromNsName
|
55 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_getAttributeValue)(struct LxmlElement *, PyObject *, PyObject *) = 0;
|
56 |
+
#define getAttributeValue __pyx_api_f_4lxml_5etree_getAttributeValue
|
57 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_iterattributes)(struct LxmlElement *, int) = 0;
|
58 |
+
#define iterattributes __pyx_api_f_4lxml_5etree_iterattributes
|
59 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_collectAttributes)(xmlNode *, int) = 0;
|
60 |
+
#define collectAttributes __pyx_api_f_4lxml_5etree_collectAttributes
|
61 |
+
static int (*__pyx_api_f_4lxml_5etree_setAttributeValue)(struct LxmlElement *, PyObject *, PyObject *) = 0;
|
62 |
+
#define setAttributeValue __pyx_api_f_4lxml_5etree_setAttributeValue
|
63 |
+
static int (*__pyx_api_f_4lxml_5etree_delAttribute)(struct LxmlElement *, PyObject *) = 0;
|
64 |
+
#define delAttribute __pyx_api_f_4lxml_5etree_delAttribute
|
65 |
+
static int (*__pyx_api_f_4lxml_5etree_delAttributeFromNsName)(xmlNode *, const xmlChar *, const xmlChar *) = 0;
|
66 |
+
#define delAttributeFromNsName __pyx_api_f_4lxml_5etree_delAttributeFromNsName
|
67 |
+
static int (*__pyx_api_f_4lxml_5etree_hasChild)(xmlNode *) = 0;
|
68 |
+
#define hasChild __pyx_api_f_4lxml_5etree_hasChild
|
69 |
+
static xmlNode *(*__pyx_api_f_4lxml_5etree_findChild)(xmlNode *, Py_ssize_t) = 0;
|
70 |
+
#define findChild __pyx_api_f_4lxml_5etree_findChild
|
71 |
+
static xmlNode *(*__pyx_api_f_4lxml_5etree_findChildForwards)(xmlNode *, Py_ssize_t) = 0;
|
72 |
+
#define findChildForwards __pyx_api_f_4lxml_5etree_findChildForwards
|
73 |
+
static xmlNode *(*__pyx_api_f_4lxml_5etree_findChildBackwards)(xmlNode *, Py_ssize_t) = 0;
|
74 |
+
#define findChildBackwards __pyx_api_f_4lxml_5etree_findChildBackwards
|
75 |
+
static xmlNode *(*__pyx_api_f_4lxml_5etree_nextElement)(xmlNode *) = 0;
|
76 |
+
#define nextElement __pyx_api_f_4lxml_5etree_nextElement
|
77 |
+
static xmlNode *(*__pyx_api_f_4lxml_5etree_previousElement)(xmlNode *) = 0;
|
78 |
+
#define previousElement __pyx_api_f_4lxml_5etree_previousElement
|
79 |
+
static void (*__pyx_api_f_4lxml_5etree_appendChild)(struct LxmlElement *, struct LxmlElement *) = 0;
|
80 |
+
#define appendChild __pyx_api_f_4lxml_5etree_appendChild
|
81 |
+
static int (*__pyx_api_f_4lxml_5etree_appendChildToElement)(struct LxmlElement *, struct LxmlElement *) = 0;
|
82 |
+
#define appendChildToElement __pyx_api_f_4lxml_5etree_appendChildToElement
|
83 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_pyunicode)(const xmlChar *) = 0;
|
84 |
+
#define pyunicode __pyx_api_f_4lxml_5etree_pyunicode
|
85 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_utf8)(PyObject *) = 0;
|
86 |
+
#define utf8 __pyx_api_f_4lxml_5etree_utf8
|
87 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_getNsTag)(PyObject *) = 0;
|
88 |
+
#define getNsTag __pyx_api_f_4lxml_5etree_getNsTag
|
89 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs)(PyObject *) = 0;
|
90 |
+
#define getNsTagWithEmptyNs __pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs
|
91 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_namespacedName)(xmlNode *) = 0;
|
92 |
+
#define namespacedName __pyx_api_f_4lxml_5etree_namespacedName
|
93 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_namespacedNameFromNsName)(const xmlChar *, const xmlChar *) = 0;
|
94 |
+
#define namespacedNameFromNsName __pyx_api_f_4lxml_5etree_namespacedNameFromNsName
|
95 |
+
static void (*__pyx_api_f_4lxml_5etree_iteratorStoreNext)(struct LxmlElementIterator *, struct LxmlElement *) = 0;
|
96 |
+
#define iteratorStoreNext __pyx_api_f_4lxml_5etree_iteratorStoreNext
|
97 |
+
static void (*__pyx_api_f_4lxml_5etree_initTagMatch)(struct LxmlElementTagMatcher *, PyObject *) = 0;
|
98 |
+
#define initTagMatch __pyx_api_f_4lxml_5etree_initTagMatch
|
99 |
+
static xmlNs *(*__pyx_api_f_4lxml_5etree_findOrBuildNodeNsPrefix)(struct LxmlDocument *, xmlNode *, const xmlChar *, const xmlChar *) = 0;
|
100 |
+
#define findOrBuildNodeNsPrefix __pyx_api_f_4lxml_5etree_findOrBuildNodeNsPrefix
|
101 |
+
#ifndef __PYX_HAVE_RT_ImportFunction_3_0_10
|
102 |
+
#define __PYX_HAVE_RT_ImportFunction_3_0_10
|
103 |
+
static int __Pyx_ImportFunction_3_0_10(PyObject *module, const char *funcname, void (**f)(void), const char *sig) {
|
104 |
+
PyObject *d = 0;
|
105 |
+
PyObject *cobj = 0;
|
106 |
+
union {
|
107 |
+
void (*fp)(void);
|
108 |
+
void *p;
|
109 |
+
} tmp;
|
110 |
+
d = PyObject_GetAttrString(module, (char *)"__pyx_capi__");
|
111 |
+
if (!d)
|
112 |
+
goto bad;
|
113 |
+
cobj = PyDict_GetItemString(d, funcname);
|
114 |
+
if (!cobj) {
|
115 |
+
PyErr_Format(PyExc_ImportError,
|
116 |
+
"%.200s does not export expected C function %.200s",
|
117 |
+
PyModule_GetName(module), funcname);
|
118 |
+
goto bad;
|
119 |
+
}
|
120 |
+
if (!PyCapsule_IsValid(cobj, sig)) {
|
121 |
+
PyErr_Format(PyExc_TypeError,
|
122 |
+
"C function %.200s.%.200s has wrong signature (expected %.500s, got %.500s)",
|
123 |
+
PyModule_GetName(module), funcname, sig, PyCapsule_GetName(cobj));
|
124 |
+
goto bad;
|
125 |
+
}
|
126 |
+
tmp.p = PyCapsule_GetPointer(cobj, sig);
|
127 |
+
*f = tmp.fp;
|
128 |
+
if (!(*f))
|
129 |
+
goto bad;
|
130 |
+
Py_DECREF(d);
|
131 |
+
return 0;
|
132 |
+
bad:
|
133 |
+
Py_XDECREF(d);
|
134 |
+
return -1;
|
135 |
+
}
|
136 |
+
#endif
|
137 |
+
|
138 |
+
|
139 |
+
static int import_lxml__etree(void) {
|
140 |
+
PyObject *module = 0;
|
141 |
+
module = PyImport_ImportModule("lxml.etree");
|
142 |
+
if (!module) goto bad;
|
143 |
+
if (__Pyx_ImportFunction_3_0_10(module, "deepcopyNodeToDocument", (void (**)(void))&__pyx_api_f_4lxml_5etree_deepcopyNodeToDocument, "struct LxmlElement *(struct LxmlDocument *, xmlNode *)") < 0) goto bad;
|
144 |
+
if (__Pyx_ImportFunction_3_0_10(module, "elementTreeFactory", (void (**)(void))&__pyx_api_f_4lxml_5etree_elementTreeFactory, "struct LxmlElementTree *(struct LxmlElement *)") < 0) goto bad;
|
145 |
+
if (__Pyx_ImportFunction_3_0_10(module, "newElementTree", (void (**)(void))&__pyx_api_f_4lxml_5etree_newElementTree, "struct LxmlElementTree *(struct LxmlElement *, PyObject *)") < 0) goto bad;
|
146 |
+
if (__Pyx_ImportFunction_3_0_10(module, "adoptExternalDocument", (void (**)(void))&__pyx_api_f_4lxml_5etree_adoptExternalDocument, "struct LxmlElementTree *(xmlDoc *, PyObject *, int)") < 0) goto bad;
|
147 |
+
if (__Pyx_ImportFunction_3_0_10(module, "elementFactory", (void (**)(void))&__pyx_api_f_4lxml_5etree_elementFactory, "struct LxmlElement *(struct LxmlDocument *, xmlNode *)") < 0) goto bad;
|
148 |
+
if (__Pyx_ImportFunction_3_0_10(module, "makeElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_makeElement, "struct LxmlElement *(PyObject *, struct LxmlDocument *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *)") < 0) goto bad;
|
149 |
+
if (__Pyx_ImportFunction_3_0_10(module, "makeSubElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_makeSubElement, "struct LxmlElement *(struct LxmlElement *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *)") < 0) goto bad;
|
150 |
+
if (__Pyx_ImportFunction_3_0_10(module, "setElementClassLookupFunction", (void (**)(void))&__pyx_api_f_4lxml_5etree_setElementClassLookupFunction, "void (_element_class_lookup_function, PyObject *)") < 0) goto bad;
|
151 |
+
if (__Pyx_ImportFunction_3_0_10(module, "lookupDefaultElementClass", (void (**)(void))&__pyx_api_f_4lxml_5etree_lookupDefaultElementClass, "PyObject *(PyObject *, PyObject *, xmlNode *)") < 0) goto bad;
|
152 |
+
if (__Pyx_ImportFunction_3_0_10(module, "lookupNamespaceElementClass", (void (**)(void))&__pyx_api_f_4lxml_5etree_lookupNamespaceElementClass, "PyObject *(PyObject *, PyObject *, xmlNode *)") < 0) goto bad;
|
153 |
+
if (__Pyx_ImportFunction_3_0_10(module, "callLookupFallback", (void (**)(void))&__pyx_api_f_4lxml_5etree_callLookupFallback, "PyObject *(struct LxmlFallbackElementClassLookup *, struct LxmlDocument *, xmlNode *)") < 0) goto bad;
|
154 |
+
if (__Pyx_ImportFunction_3_0_10(module, "tagMatches", (void (**)(void))&__pyx_api_f_4lxml_5etree_tagMatches, "int (xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad;
|
155 |
+
if (__Pyx_ImportFunction_3_0_10(module, "documentOrRaise", (void (**)(void))&__pyx_api_f_4lxml_5etree_documentOrRaise, "struct LxmlDocument *(PyObject *)") < 0) goto bad;
|
156 |
+
if (__Pyx_ImportFunction_3_0_10(module, "rootNodeOrRaise", (void (**)(void))&__pyx_api_f_4lxml_5etree_rootNodeOrRaise, "struct LxmlElement *(PyObject *)") < 0) goto bad;
|
157 |
+
if (__Pyx_ImportFunction_3_0_10(module, "hasText", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasText, "int (xmlNode *)") < 0) goto bad;
|
158 |
+
if (__Pyx_ImportFunction_3_0_10(module, "hasTail", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasTail, "int (xmlNode *)") < 0) goto bad;
|
159 |
+
if (__Pyx_ImportFunction_3_0_10(module, "textOf", (void (**)(void))&__pyx_api_f_4lxml_5etree_textOf, "PyObject *(xmlNode *)") < 0) goto bad;
|
160 |
+
if (__Pyx_ImportFunction_3_0_10(module, "tailOf", (void (**)(void))&__pyx_api_f_4lxml_5etree_tailOf, "PyObject *(xmlNode *)") < 0) goto bad;
|
161 |
+
if (__Pyx_ImportFunction_3_0_10(module, "setNodeText", (void (**)(void))&__pyx_api_f_4lxml_5etree_setNodeText, "int (xmlNode *, PyObject *)") < 0) goto bad;
|
162 |
+
if (__Pyx_ImportFunction_3_0_10(module, "setTailText", (void (**)(void))&__pyx_api_f_4lxml_5etree_setTailText, "int (xmlNode *, PyObject *)") < 0) goto bad;
|
163 |
+
if (__Pyx_ImportFunction_3_0_10(module, "attributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_attributeValue, "PyObject *(xmlNode *, xmlAttr *)") < 0) goto bad;
|
164 |
+
if (__Pyx_ImportFunction_3_0_10(module, "attributeValueFromNsName", (void (**)(void))&__pyx_api_f_4lxml_5etree_attributeValueFromNsName, "PyObject *(xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad;
|
165 |
+
if (__Pyx_ImportFunction_3_0_10(module, "getAttributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_getAttributeValue, "PyObject *(struct LxmlElement *, PyObject *, PyObject *)") < 0) goto bad;
|
166 |
+
if (__Pyx_ImportFunction_3_0_10(module, "iterattributes", (void (**)(void))&__pyx_api_f_4lxml_5etree_iterattributes, "PyObject *(struct LxmlElement *, int)") < 0) goto bad;
|
167 |
+
if (__Pyx_ImportFunction_3_0_10(module, "collectAttributes", (void (**)(void))&__pyx_api_f_4lxml_5etree_collectAttributes, "PyObject *(xmlNode *, int)") < 0) goto bad;
|
168 |
+
if (__Pyx_ImportFunction_3_0_10(module, "setAttributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_setAttributeValue, "int (struct LxmlElement *, PyObject *, PyObject *)") < 0) goto bad;
|
169 |
+
if (__Pyx_ImportFunction_3_0_10(module, "delAttribute", (void (**)(void))&__pyx_api_f_4lxml_5etree_delAttribute, "int (struct LxmlElement *, PyObject *)") < 0) goto bad;
|
170 |
+
if (__Pyx_ImportFunction_3_0_10(module, "delAttributeFromNsName", (void (**)(void))&__pyx_api_f_4lxml_5etree_delAttributeFromNsName, "int (xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad;
|
171 |
+
if (__Pyx_ImportFunction_3_0_10(module, "hasChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasChild, "int (xmlNode *)") < 0) goto bad;
|
172 |
+
if (__Pyx_ImportFunction_3_0_10(module, "findChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChild, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad;
|
173 |
+
if (__Pyx_ImportFunction_3_0_10(module, "findChildForwards", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChildForwards, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad;
|
174 |
+
if (__Pyx_ImportFunction_3_0_10(module, "findChildBackwards", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChildBackwards, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad;
|
175 |
+
if (__Pyx_ImportFunction_3_0_10(module, "nextElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_nextElement, "xmlNode *(xmlNode *)") < 0) goto bad;
|
176 |
+
if (__Pyx_ImportFunction_3_0_10(module, "previousElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_previousElement, "xmlNode *(xmlNode *)") < 0) goto bad;
|
177 |
+
if (__Pyx_ImportFunction_3_0_10(module, "appendChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_appendChild, "void (struct LxmlElement *, struct LxmlElement *)") < 0) goto bad;
|
178 |
+
if (__Pyx_ImportFunction_3_0_10(module, "appendChildToElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_appendChildToElement, "int (struct LxmlElement *, struct LxmlElement *)") < 0) goto bad;
|
179 |
+
if (__Pyx_ImportFunction_3_0_10(module, "pyunicode", (void (**)(void))&__pyx_api_f_4lxml_5etree_pyunicode, "PyObject *(const xmlChar *)") < 0) goto bad;
|
180 |
+
if (__Pyx_ImportFunction_3_0_10(module, "utf8", (void (**)(void))&__pyx_api_f_4lxml_5etree_utf8, "PyObject *(PyObject *)") < 0) goto bad;
|
181 |
+
if (__Pyx_ImportFunction_3_0_10(module, "getNsTag", (void (**)(void))&__pyx_api_f_4lxml_5etree_getNsTag, "PyObject *(PyObject *)") < 0) goto bad;
|
182 |
+
if (__Pyx_ImportFunction_3_0_10(module, "getNsTagWithEmptyNs", (void (**)(void))&__pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs, "PyObject *(PyObject *)") < 0) goto bad;
|
183 |
+
if (__Pyx_ImportFunction_3_0_10(module, "namespacedName", (void (**)(void))&__pyx_api_f_4lxml_5etree_namespacedName, "PyObject *(xmlNode *)") < 0) goto bad;
|
184 |
+
if (__Pyx_ImportFunction_3_0_10(module, "namespacedNameFromNsName", (void (**)(void))&__pyx_api_f_4lxml_5etree_namespacedNameFromNsName, "PyObject *(const xmlChar *, const xmlChar *)") < 0) goto bad;
|
185 |
+
if (__Pyx_ImportFunction_3_0_10(module, "iteratorStoreNext", (void (**)(void))&__pyx_api_f_4lxml_5etree_iteratorStoreNext, "void (struct LxmlElementIterator *, struct LxmlElement *)") < 0) goto bad;
|
186 |
+
if (__Pyx_ImportFunction_3_0_10(module, "initTagMatch", (void (**)(void))&__pyx_api_f_4lxml_5etree_initTagMatch, "void (struct LxmlElementTagMatcher *, PyObject *)") < 0) goto bad;
|
187 |
+
if (__Pyx_ImportFunction_3_0_10(module, "findOrBuildNodeNsPrefix", (void (**)(void))&__pyx_api_f_4lxml_5etree_findOrBuildNodeNsPrefix, "xmlNs *(struct LxmlDocument *, xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad;
|
188 |
+
Py_DECREF(module); module = 0;
|
189 |
+
return 0;
|
190 |
+
bad:
|
191 |
+
Py_XDECREF(module);
|
192 |
+
return -1;
|
193 |
+
}
|
194 |
+
|
195 |
+
#endif /* !__PYX_HAVE_API__lxml__etree */
|
llmeval-env/lib/python3.10/site-packages/lxml/objectify.pyx
ADDED
@@ -0,0 +1,2145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# cython: binding=True
|
2 |
+
# cython: auto_pickle=False
|
3 |
+
# cython: language_level=3
|
4 |
+
|
5 |
+
"""
|
6 |
+
The ``lxml.objectify`` module implements a Python object API for XML.
|
7 |
+
It is based on `lxml.etree`.
|
8 |
+
"""
|
9 |
+
|
10 |
+
cimport cython
|
11 |
+
|
12 |
+
from lxml.includes.etreepublic cimport _Document, _Element, ElementBase, ElementClassLookup
|
13 |
+
from lxml.includes.etreepublic cimport elementFactory, import_lxml__etree, textOf, pyunicode
|
14 |
+
from lxml.includes.tree cimport const_xmlChar, _xcstr
|
15 |
+
from lxml cimport python
|
16 |
+
from lxml.includes cimport tree
|
17 |
+
|
18 |
+
cimport lxml.includes.etreepublic as cetree
|
19 |
+
cimport libc.string as cstring_h # not to be confused with stdlib 'string'
|
20 |
+
from libc.string cimport const_char
|
21 |
+
|
22 |
+
__all__ = ['BoolElement', 'DataElement', 'E', 'Element', 'ElementMaker',
|
23 |
+
'FloatElement', 'IntElement', 'NoneElement',
|
24 |
+
'NumberElement', 'ObjectPath', 'ObjectifiedDataElement',
|
25 |
+
'ObjectifiedElement', 'ObjectifyElementClassLookup',
|
26 |
+
'PYTYPE_ATTRIBUTE', 'PyType', 'StringElement', 'SubElement',
|
27 |
+
'XML', 'annotate', 'deannotate', 'dump', 'enable_recursive_str',
|
28 |
+
'fromstring', 'getRegisteredTypes', 'makeparser', 'parse',
|
29 |
+
'pyannotate', 'pytypename', 'set_default_parser',
|
30 |
+
'set_pytype_attribute_tag', 'xsiannotate']
|
31 |
+
|
32 |
+
cdef object etree
|
33 |
+
from lxml import etree
|
34 |
+
# initialize C-API of lxml.etree
|
35 |
+
import_lxml__etree()
|
36 |
+
|
37 |
+
__version__ = etree.__version__
|
38 |
+
|
39 |
+
cdef object _float_is_inf, _float_is_nan
|
40 |
+
from math import isinf as _float_is_inf, isnan as _float_is_nan
|
41 |
+
|
42 |
+
cdef object re
|
43 |
+
import re
|
44 |
+
|
45 |
+
cdef tuple IGNORABLE_ERRORS = (ValueError, TypeError)
|
46 |
+
cdef object is_special_method = re.compile('__.*__$').match
|
47 |
+
|
48 |
+
|
49 |
+
cdef object _typename(object t):
|
50 |
+
cdef const_char* c_name
|
51 |
+
c_name = python._fqtypename(t)
|
52 |
+
s = cstring_h.strrchr(c_name, c'.')
|
53 |
+
if s is not NULL:
|
54 |
+
c_name = s + 1
|
55 |
+
return pyunicode(<const_xmlChar*>c_name)
|
56 |
+
|
57 |
+
|
58 |
+
# namespace/name for "pytype" hint attribute
|
59 |
+
cdef object PYTYPE_NAMESPACE
|
60 |
+
cdef bytes PYTYPE_NAMESPACE_UTF8
|
61 |
+
cdef const_xmlChar* _PYTYPE_NAMESPACE
|
62 |
+
|
63 |
+
cdef object PYTYPE_ATTRIBUTE_NAME
|
64 |
+
cdef bytes PYTYPE_ATTRIBUTE_NAME_UTF8
|
65 |
+
cdef const_xmlChar* _PYTYPE_ATTRIBUTE_NAME
|
66 |
+
|
67 |
+
PYTYPE_ATTRIBUTE = None
|
68 |
+
|
69 |
+
cdef unicode TREE_PYTYPE_NAME = "TREE"
|
70 |
+
|
71 |
+
cdef tuple _unicodeAndUtf8(s):
|
72 |
+
return s, python.PyUnicode_AsUTF8String(s)
|
73 |
+
|
74 |
+
def set_pytype_attribute_tag(attribute_tag=None):
|
75 |
+
"""set_pytype_attribute_tag(attribute_tag=None)
|
76 |
+
Change name and namespace of the XML attribute that holds Python type
|
77 |
+
information.
|
78 |
+
|
79 |
+
Do not use this unless you know what you are doing.
|
80 |
+
|
81 |
+
Reset by calling without argument.
|
82 |
+
|
83 |
+
Default: "{http://codespeak.net/lxml/objectify/pytype}pytype"
|
84 |
+
"""
|
85 |
+
global PYTYPE_ATTRIBUTE, _PYTYPE_NAMESPACE, _PYTYPE_ATTRIBUTE_NAME
|
86 |
+
global PYTYPE_NAMESPACE, PYTYPE_NAMESPACE_UTF8
|
87 |
+
global PYTYPE_ATTRIBUTE_NAME, PYTYPE_ATTRIBUTE_NAME_UTF8
|
88 |
+
if attribute_tag is None:
|
89 |
+
PYTYPE_NAMESPACE, PYTYPE_NAMESPACE_UTF8 = \
|
90 |
+
_unicodeAndUtf8("http://codespeak.net/lxml/objectify/pytype")
|
91 |
+
PYTYPE_ATTRIBUTE_NAME, PYTYPE_ATTRIBUTE_NAME_UTF8 = \
|
92 |
+
_unicodeAndUtf8("pytype")
|
93 |
+
else:
|
94 |
+
PYTYPE_NAMESPACE_UTF8, PYTYPE_ATTRIBUTE_NAME_UTF8 = \
|
95 |
+
cetree.getNsTag(attribute_tag)
|
96 |
+
PYTYPE_NAMESPACE = PYTYPE_NAMESPACE_UTF8.decode('utf8')
|
97 |
+
PYTYPE_ATTRIBUTE_NAME = PYTYPE_ATTRIBUTE_NAME_UTF8.decode('utf8')
|
98 |
+
|
99 |
+
_PYTYPE_NAMESPACE = PYTYPE_NAMESPACE_UTF8
|
100 |
+
_PYTYPE_ATTRIBUTE_NAME = PYTYPE_ATTRIBUTE_NAME_UTF8
|
101 |
+
PYTYPE_ATTRIBUTE = cetree.namespacedNameFromNsName(
|
102 |
+
_PYTYPE_NAMESPACE, _PYTYPE_ATTRIBUTE_NAME)
|
103 |
+
|
104 |
+
set_pytype_attribute_tag()
|
105 |
+
|
106 |
+
|
107 |
+
# namespaces for XML Schema
|
108 |
+
cdef object XML_SCHEMA_NS, XML_SCHEMA_NS_UTF8
|
109 |
+
XML_SCHEMA_NS, XML_SCHEMA_NS_UTF8 = \
|
110 |
+
_unicodeAndUtf8("http://www.w3.org/2001/XMLSchema")
|
111 |
+
cdef const_xmlChar* _XML_SCHEMA_NS = _xcstr(XML_SCHEMA_NS_UTF8)
|
112 |
+
|
113 |
+
cdef object XML_SCHEMA_INSTANCE_NS, XML_SCHEMA_INSTANCE_NS_UTF8
|
114 |
+
XML_SCHEMA_INSTANCE_NS, XML_SCHEMA_INSTANCE_NS_UTF8 = \
|
115 |
+
_unicodeAndUtf8("http://www.w3.org/2001/XMLSchema-instance")
|
116 |
+
cdef const_xmlChar* _XML_SCHEMA_INSTANCE_NS = _xcstr(XML_SCHEMA_INSTANCE_NS_UTF8)
|
117 |
+
|
118 |
+
cdef object XML_SCHEMA_INSTANCE_NIL_ATTR = "{%s}nil" % XML_SCHEMA_INSTANCE_NS
|
119 |
+
cdef object XML_SCHEMA_INSTANCE_TYPE_ATTR = "{%s}type" % XML_SCHEMA_INSTANCE_NS
|
120 |
+
|
121 |
+
|
122 |
+
################################################################################
|
123 |
+
# Element class for the main API
|
124 |
+
|
125 |
+
cdef class ObjectifiedElement(ElementBase):
|
126 |
+
"""Main XML Element class.
|
127 |
+
|
128 |
+
Element children are accessed as object attributes. Multiple children
|
129 |
+
with the same name are available through a list index. Example::
|
130 |
+
|
131 |
+
>>> root = XML("<root><c1><c2>0</c2><c2>1</c2></c1></root>")
|
132 |
+
>>> second_c2 = root.c1.c2[1]
|
133 |
+
>>> print(second_c2.text)
|
134 |
+
1
|
135 |
+
|
136 |
+
Note that you cannot (and must not) instantiate this class or its
|
137 |
+
subclasses.
|
138 |
+
"""
|
139 |
+
def __iter__(self):
|
140 |
+
"""Iterate over self and all siblings with the same tag.
|
141 |
+
"""
|
142 |
+
parent = self.getparent()
|
143 |
+
if parent is None:
|
144 |
+
return iter([self])
|
145 |
+
return etree.ElementChildIterator(parent, tag=self.tag)
|
146 |
+
|
147 |
+
def __str__(self):
|
148 |
+
if __RECURSIVE_STR:
|
149 |
+
return _dump(self, 0)
|
150 |
+
else:
|
151 |
+
return textOf(self._c_node) or ''
|
152 |
+
|
153 |
+
# pickle support for objectified Element
|
154 |
+
def __reduce__(self):
|
155 |
+
return fromstring, (etree.tostring(self),)
|
156 |
+
|
157 |
+
@property
|
158 |
+
def text(self):
|
159 |
+
return textOf(self._c_node)
|
160 |
+
|
161 |
+
@property
|
162 |
+
def __dict__(self):
|
163 |
+
"""A fake implementation for __dict__ to support dir() etc.
|
164 |
+
|
165 |
+
Note that this only considers the first child with a given name.
|
166 |
+
"""
|
167 |
+
cdef _Element child
|
168 |
+
cdef dict children
|
169 |
+
c_ns = tree._getNs(self._c_node)
|
170 |
+
tag = "{%s}*" % pyunicode(c_ns) if c_ns is not NULL else None
|
171 |
+
children = {}
|
172 |
+
for child in etree.ElementChildIterator(self, tag=tag):
|
173 |
+
if c_ns is NULL and tree._getNs(child._c_node) is not NULL:
|
174 |
+
continue
|
175 |
+
name = pyunicode(child._c_node.name)
|
176 |
+
if name not in children:
|
177 |
+
children[name] = child
|
178 |
+
return children
|
179 |
+
|
180 |
+
def __len__(self):
|
181 |
+
"""Count self and siblings with the same tag.
|
182 |
+
"""
|
183 |
+
return _countSiblings(self._c_node)
|
184 |
+
|
185 |
+
def countchildren(self):
|
186 |
+
"""countchildren(self)
|
187 |
+
|
188 |
+
Return the number of children of this element, regardless of their
|
189 |
+
name.
|
190 |
+
"""
|
191 |
+
# copied from etree
|
192 |
+
cdef Py_ssize_t c
|
193 |
+
cdef tree.xmlNode* c_node
|
194 |
+
c = 0
|
195 |
+
c_node = self._c_node.children
|
196 |
+
while c_node is not NULL:
|
197 |
+
if tree._isElement(c_node):
|
198 |
+
c += 1
|
199 |
+
c_node = c_node.next
|
200 |
+
return c
|
201 |
+
|
202 |
+
def getchildren(self):
|
203 |
+
"""getchildren(self)
|
204 |
+
|
205 |
+
Returns a sequence of all direct children. The elements are
|
206 |
+
returned in document order.
|
207 |
+
"""
|
208 |
+
cdef tree.xmlNode* c_node
|
209 |
+
result = []
|
210 |
+
c_node = self._c_node.children
|
211 |
+
while c_node is not NULL:
|
212 |
+
if tree._isElement(c_node):
|
213 |
+
result.append(cetree.elementFactory(self._doc, c_node))
|
214 |
+
c_node = c_node.next
|
215 |
+
return result
|
216 |
+
|
217 |
+
def __getattr__(self, tag):
|
218 |
+
"""Return the (first) child with the given tag name. If no namespace
|
219 |
+
is provided, the child will be looked up in the same one as self.
|
220 |
+
"""
|
221 |
+
return _lookupChildOrRaise(self, tag)
|
222 |
+
|
223 |
+
def __setattr__(self, tag, value):
|
224 |
+
"""Set the value of the (first) child with the given tag name. If no
|
225 |
+
namespace is provided, the child will be looked up in the same one as
|
226 |
+
self.
|
227 |
+
"""
|
228 |
+
cdef _Element element
|
229 |
+
# properties are looked up /after/ __setattr__, so we must emulate them
|
230 |
+
if tag == 'text' or tag == 'pyval':
|
231 |
+
# read-only !
|
232 |
+
raise TypeError, f"attribute '{tag}' of '{_typename(self)}' objects is not writable"
|
233 |
+
elif tag == 'tail':
|
234 |
+
cetree.setTailText(self._c_node, value)
|
235 |
+
return
|
236 |
+
elif tag == 'tag':
|
237 |
+
ElementBase.tag.__set__(self, value)
|
238 |
+
return
|
239 |
+
elif tag == 'base':
|
240 |
+
ElementBase.base.__set__(self, value)
|
241 |
+
return
|
242 |
+
tag = _buildChildTag(self, tag)
|
243 |
+
element = _lookupChild(self, tag)
|
244 |
+
if element is None:
|
245 |
+
_appendValue(self, tag, value)
|
246 |
+
else:
|
247 |
+
_replaceElement(element, value)
|
248 |
+
|
249 |
+
def __delattr__(self, tag):
|
250 |
+
child = _lookupChildOrRaise(self, tag)
|
251 |
+
self.remove(child)
|
252 |
+
|
253 |
+
def addattr(self, tag, value):
|
254 |
+
"""addattr(self, tag, value)
|
255 |
+
|
256 |
+
Add a child value to the element.
|
257 |
+
|
258 |
+
As opposed to append(), it sets a data value, not an element.
|
259 |
+
"""
|
260 |
+
_appendValue(self, _buildChildTag(self, tag), value)
|
261 |
+
|
262 |
+
def __getitem__(self, key):
|
263 |
+
"""Return a sibling, counting from the first child of the parent. The
|
264 |
+
method behaves like both a dict and a sequence.
|
265 |
+
|
266 |
+
* If argument is an integer, returns the sibling at that position.
|
267 |
+
|
268 |
+
* If argument is a string, does the same as getattr(). This can be
|
269 |
+
used to provide namespaces for element lookup, or to look up
|
270 |
+
children with special names (``text`` etc.).
|
271 |
+
|
272 |
+
* If argument is a slice object, returns the matching slice.
|
273 |
+
"""
|
274 |
+
cdef tree.xmlNode* c_self_node
|
275 |
+
cdef tree.xmlNode* c_parent
|
276 |
+
cdef tree.xmlNode* c_node
|
277 |
+
cdef Py_ssize_t c_index
|
278 |
+
if python._isString(key):
|
279 |
+
return _lookupChildOrRaise(self, key)
|
280 |
+
elif isinstance(key, slice):
|
281 |
+
return list(self)[key]
|
282 |
+
# normal item access
|
283 |
+
c_index = key # raises TypeError if necessary
|
284 |
+
c_self_node = self._c_node
|
285 |
+
c_parent = c_self_node.parent
|
286 |
+
if c_parent is NULL:
|
287 |
+
if c_index == 0 or c_index == -1:
|
288 |
+
return self
|
289 |
+
raise IndexError, unicode(key)
|
290 |
+
if c_index < 0:
|
291 |
+
c_node = c_parent.last
|
292 |
+
else:
|
293 |
+
c_node = c_parent.children
|
294 |
+
c_node = _findFollowingSibling(
|
295 |
+
c_node, tree._getNs(c_self_node), c_self_node.name, c_index)
|
296 |
+
if c_node is NULL:
|
297 |
+
raise IndexError, unicode(key)
|
298 |
+
return elementFactory(self._doc, c_node)
|
299 |
+
|
300 |
+
def __setitem__(self, key, value):
|
301 |
+
"""Set the value of a sibling, counting from the first child of the
|
302 |
+
parent. Implements key assignment, item assignment and slice
|
303 |
+
assignment.
|
304 |
+
|
305 |
+
* If argument is an integer, sets the sibling at that position.
|
306 |
+
|
307 |
+
* If argument is a string, does the same as setattr(). This is used
|
308 |
+
to provide namespaces for element lookup.
|
309 |
+
|
310 |
+
* If argument is a sequence (list, tuple, etc.), assign the contained
|
311 |
+
items to the siblings.
|
312 |
+
"""
|
313 |
+
cdef _Element element
|
314 |
+
cdef tree.xmlNode* c_node
|
315 |
+
if python._isString(key):
|
316 |
+
key = _buildChildTag(self, key)
|
317 |
+
element = _lookupChild(self, key)
|
318 |
+
if element is None:
|
319 |
+
_appendValue(self, key, value)
|
320 |
+
else:
|
321 |
+
_replaceElement(element, value)
|
322 |
+
return
|
323 |
+
|
324 |
+
if self._c_node.parent is NULL:
|
325 |
+
# the 'root[i] = ...' case
|
326 |
+
raise TypeError, "assignment to root element is invalid"
|
327 |
+
|
328 |
+
if isinstance(key, slice):
|
329 |
+
# slice assignment
|
330 |
+
_setSlice(key, self, value)
|
331 |
+
else:
|
332 |
+
# normal index assignment
|
333 |
+
if key < 0:
|
334 |
+
c_node = self._c_node.parent.last
|
335 |
+
else:
|
336 |
+
c_node = self._c_node.parent.children
|
337 |
+
c_node = _findFollowingSibling(
|
338 |
+
c_node, tree._getNs(self._c_node), self._c_node.name, key)
|
339 |
+
if c_node is NULL:
|
340 |
+
raise IndexError, unicode(key)
|
341 |
+
element = elementFactory(self._doc, c_node)
|
342 |
+
_replaceElement(element, value)
|
343 |
+
|
344 |
+
def __delitem__(self, key):
|
345 |
+
parent = self.getparent()
|
346 |
+
if parent is None:
|
347 |
+
raise TypeError, "deleting items not supported by root element"
|
348 |
+
if isinstance(key, slice):
|
349 |
+
# slice deletion
|
350 |
+
del_items = list(self)[key]
|
351 |
+
remove = parent.remove
|
352 |
+
for el in del_items:
|
353 |
+
remove(el)
|
354 |
+
else:
|
355 |
+
# normal index deletion
|
356 |
+
sibling = self.__getitem__(key)
|
357 |
+
parent.remove(sibling)
|
358 |
+
|
359 |
+
def descendantpaths(self, prefix=None):
|
360 |
+
"""descendantpaths(self, prefix=None)
|
361 |
+
|
362 |
+
Returns a list of object path expressions for all descendants.
|
363 |
+
"""
|
364 |
+
if prefix is not None and not python._isString(prefix):
|
365 |
+
prefix = '.'.join(prefix)
|
366 |
+
return _build_descendant_paths(self._c_node, prefix)
|
367 |
+
|
368 |
+
|
369 |
+
cdef inline bint _tagMatches(tree.xmlNode* c_node, const_xmlChar* c_href, const_xmlChar* c_name):
|
370 |
+
if c_node.name != c_name:
|
371 |
+
return 0
|
372 |
+
if c_href == NULL:
|
373 |
+
return 1
|
374 |
+
c_node_href = tree._getNs(c_node)
|
375 |
+
if c_node_href == NULL:
|
376 |
+
return c_href[0] == c'\0'
|
377 |
+
return tree.xmlStrcmp(c_node_href, c_href) == 0
|
378 |
+
|
379 |
+
|
380 |
+
cdef Py_ssize_t _countSiblings(tree.xmlNode* c_start_node):
|
381 |
+
cdef tree.xmlNode* c_node
|
382 |
+
cdef Py_ssize_t count
|
383 |
+
c_tag = c_start_node.name
|
384 |
+
c_href = tree._getNs(c_start_node)
|
385 |
+
count = 1
|
386 |
+
c_node = c_start_node.next
|
387 |
+
while c_node is not NULL:
|
388 |
+
if c_node.type == tree.XML_ELEMENT_NODE and \
|
389 |
+
_tagMatches(c_node, c_href, c_tag):
|
390 |
+
count += 1
|
391 |
+
c_node = c_node.next
|
392 |
+
c_node = c_start_node.prev
|
393 |
+
while c_node is not NULL:
|
394 |
+
if c_node.type == tree.XML_ELEMENT_NODE and \
|
395 |
+
_tagMatches(c_node, c_href, c_tag):
|
396 |
+
count += 1
|
397 |
+
c_node = c_node.prev
|
398 |
+
return count
|
399 |
+
|
400 |
+
cdef tree.xmlNode* _findFollowingSibling(tree.xmlNode* c_node,
|
401 |
+
const_xmlChar* href, const_xmlChar* name,
|
402 |
+
Py_ssize_t index):
|
403 |
+
cdef tree.xmlNode* (*next)(tree.xmlNode*)
|
404 |
+
if index >= 0:
|
405 |
+
next = cetree.nextElement
|
406 |
+
else:
|
407 |
+
index = -1 - index
|
408 |
+
next = cetree.previousElement
|
409 |
+
while c_node is not NULL:
|
410 |
+
if c_node.type == tree.XML_ELEMENT_NODE and \
|
411 |
+
_tagMatches(c_node, href, name):
|
412 |
+
index = index - 1
|
413 |
+
if index < 0:
|
414 |
+
return c_node
|
415 |
+
c_node = next(c_node)
|
416 |
+
return NULL
|
417 |
+
|
418 |
+
cdef object _lookupChild(_Element parent, tag):
|
419 |
+
cdef tree.xmlNode* c_result
|
420 |
+
cdef tree.xmlNode* c_node
|
421 |
+
c_node = parent._c_node
|
422 |
+
ns, tag = cetree.getNsTagWithEmptyNs(tag)
|
423 |
+
c_tag = tree.xmlDictExists(
|
424 |
+
c_node.doc.dict, _xcstr(tag), python.PyBytes_GET_SIZE(tag))
|
425 |
+
if c_tag is NULL:
|
426 |
+
return None # not in the hash map => not in the tree
|
427 |
+
if ns is None:
|
428 |
+
# either inherit ns from parent or use empty (i.e. no) namespace
|
429 |
+
c_href = tree._getNs(c_node) or <const_xmlChar*>''
|
430 |
+
else:
|
431 |
+
c_href = _xcstr(ns)
|
432 |
+
c_result = _findFollowingSibling(c_node.children, c_href, c_tag, 0)
|
433 |
+
if c_result is NULL:
|
434 |
+
return None
|
435 |
+
return elementFactory(parent._doc, c_result)
|
436 |
+
|
437 |
+
cdef object _lookupChildOrRaise(_Element parent, tag):
|
438 |
+
element = _lookupChild(parent, tag)
|
439 |
+
if element is None:
|
440 |
+
raise AttributeError, "no such child: " + _buildChildTag(parent, tag)
|
441 |
+
return element
|
442 |
+
|
443 |
+
cdef object _buildChildTag(_Element parent, tag):
|
444 |
+
ns, tag = cetree.getNsTag(tag)
|
445 |
+
c_tag = _xcstr(tag)
|
446 |
+
c_href = tree._getNs(parent._c_node) if ns is None else _xcstr(ns)
|
447 |
+
return cetree.namespacedNameFromNsName(c_href, c_tag)
|
448 |
+
|
449 |
+
cdef _replaceElement(_Element element, value):
|
450 |
+
cdef _Element new_element
|
451 |
+
if isinstance(value, _Element):
|
452 |
+
# deep copy the new element
|
453 |
+
new_element = cetree.deepcopyNodeToDocument(
|
454 |
+
element._doc, (<_Element>value)._c_node)
|
455 |
+
new_element.tag = element.tag
|
456 |
+
elif isinstance(value, (list, tuple)):
|
457 |
+
element[:] = value
|
458 |
+
return
|
459 |
+
else:
|
460 |
+
new_element = element.makeelement(element.tag)
|
461 |
+
_setElementValue(new_element, value)
|
462 |
+
element.getparent().replace(element, new_element)
|
463 |
+
|
464 |
+
cdef _appendValue(_Element parent, tag, value):
|
465 |
+
cdef _Element new_element
|
466 |
+
if isinstance(value, _Element):
|
467 |
+
# deep copy the new element
|
468 |
+
new_element = cetree.deepcopyNodeToDocument(
|
469 |
+
parent._doc, (<_Element>value)._c_node)
|
470 |
+
new_element.tag = tag
|
471 |
+
cetree.appendChildToElement(parent, new_element)
|
472 |
+
elif isinstance(value, (list, tuple)):
|
473 |
+
for item in value:
|
474 |
+
_appendValue(parent, tag, item)
|
475 |
+
else:
|
476 |
+
new_element = cetree.makeElement(
|
477 |
+
tag, parent._doc, None, None, None, None, None)
|
478 |
+
_setElementValue(new_element, value)
|
479 |
+
cetree.appendChildToElement(parent, new_element)
|
480 |
+
|
481 |
+
cdef _setElementValue(_Element element, value):
|
482 |
+
if value is None:
|
483 |
+
cetree.setAttributeValue(
|
484 |
+
element, XML_SCHEMA_INSTANCE_NIL_ATTR, "true")
|
485 |
+
elif isinstance(value, _Element):
|
486 |
+
_replaceElement(element, value)
|
487 |
+
return
|
488 |
+
else:
|
489 |
+
cetree.delAttributeFromNsName(
|
490 |
+
element._c_node, _XML_SCHEMA_INSTANCE_NS, <unsigned char*>"nil")
|
491 |
+
if python._isString(value):
|
492 |
+
pytype_name = "str"
|
493 |
+
py_type = <PyType>_PYTYPE_DICT.get(pytype_name)
|
494 |
+
else:
|
495 |
+
pytype_name = _typename(value)
|
496 |
+
py_type = <PyType>_PYTYPE_DICT.get(pytype_name)
|
497 |
+
if py_type is not None:
|
498 |
+
value = py_type.stringify(value)
|
499 |
+
else:
|
500 |
+
value = unicode(value)
|
501 |
+
if py_type is not None:
|
502 |
+
cetree.setAttributeValue(element, PYTYPE_ATTRIBUTE, pytype_name)
|
503 |
+
else:
|
504 |
+
cetree.delAttributeFromNsName(
|
505 |
+
element._c_node, _PYTYPE_NAMESPACE, _PYTYPE_ATTRIBUTE_NAME)
|
506 |
+
cetree.setNodeText(element._c_node, value)
|
507 |
+
|
508 |
+
cdef _setSlice(sliceobject, _Element target, items):
|
509 |
+
cdef _Element parent
|
510 |
+
cdef tree.xmlNode* c_node
|
511 |
+
cdef Py_ssize_t c_step, c_start, pos
|
512 |
+
# collect existing slice
|
513 |
+
if (<slice>sliceobject).step is None:
|
514 |
+
c_step = 1
|
515 |
+
else:
|
516 |
+
c_step = (<slice>sliceobject).step
|
517 |
+
if c_step == 0:
|
518 |
+
raise ValueError, "Invalid slice"
|
519 |
+
cdef list del_items = target[sliceobject]
|
520 |
+
|
521 |
+
# collect new values
|
522 |
+
new_items = []
|
523 |
+
tag = target.tag
|
524 |
+
for item in items:
|
525 |
+
if isinstance(item, _Element):
|
526 |
+
# deep copy the new element
|
527 |
+
new_element = cetree.deepcopyNodeToDocument(
|
528 |
+
target._doc, (<_Element>item)._c_node)
|
529 |
+
new_element.tag = tag
|
530 |
+
else:
|
531 |
+
new_element = cetree.makeElement(
|
532 |
+
tag, target._doc, None, None, None, None, None)
|
533 |
+
_setElementValue(new_element, item)
|
534 |
+
new_items.append(new_element)
|
535 |
+
|
536 |
+
# sanity check - raise what a list would raise
|
537 |
+
if c_step != 1 and len(del_items) != len(new_items):
|
538 |
+
raise ValueError, \
|
539 |
+
f"attempt to assign sequence of size {len(new_items)} to extended slice of size {len(del_items)}"
|
540 |
+
|
541 |
+
# replace existing items
|
542 |
+
pos = 0
|
543 |
+
parent = target.getparent()
|
544 |
+
replace = parent.replace
|
545 |
+
while pos < len(new_items) and pos < len(del_items):
|
546 |
+
replace(del_items[pos], new_items[pos])
|
547 |
+
pos += 1
|
548 |
+
# remove leftover items
|
549 |
+
if pos < len(del_items):
|
550 |
+
remove = parent.remove
|
551 |
+
while pos < len(del_items):
|
552 |
+
remove(del_items[pos])
|
553 |
+
pos += 1
|
554 |
+
# append remaining new items
|
555 |
+
if pos < len(new_items):
|
556 |
+
# the sanity check above guarantees (step == 1)
|
557 |
+
if pos > 0:
|
558 |
+
item = new_items[pos-1]
|
559 |
+
else:
|
560 |
+
if (<slice>sliceobject).start > 0:
|
561 |
+
c_node = parent._c_node.children
|
562 |
+
else:
|
563 |
+
c_node = parent._c_node.last
|
564 |
+
c_node = _findFollowingSibling(
|
565 |
+
c_node, tree._getNs(target._c_node), target._c_node.name,
|
566 |
+
(<slice>sliceobject).start - 1)
|
567 |
+
if c_node is NULL:
|
568 |
+
while pos < len(new_items):
|
569 |
+
cetree.appendChildToElement(parent, new_items[pos])
|
570 |
+
pos += 1
|
571 |
+
return
|
572 |
+
item = cetree.elementFactory(parent._doc, c_node)
|
573 |
+
while pos < len(new_items):
|
574 |
+
add = item.addnext
|
575 |
+
item = new_items[pos]
|
576 |
+
add(item)
|
577 |
+
pos += 1
|
578 |
+
|
579 |
+
################################################################################
|
580 |
+
# Data type support in subclasses
|
581 |
+
|
582 |
+
cdef class ObjectifiedDataElement(ObjectifiedElement):
|
583 |
+
"""This is the base class for all data type Elements. Subclasses should
|
584 |
+
override the 'pyval' property and possibly the __str__ method.
|
585 |
+
"""
|
586 |
+
@property
|
587 |
+
def pyval(self):
|
588 |
+
return textOf(self._c_node)
|
589 |
+
|
590 |
+
def __str__(self):
|
591 |
+
return textOf(self._c_node) or ''
|
592 |
+
|
593 |
+
def __repr__(self):
|
594 |
+
return textOf(self._c_node) or ''
|
595 |
+
|
596 |
+
def _setText(self, s):
|
597 |
+
"""For use in subclasses only. Don't use unless you know what you are
|
598 |
+
doing.
|
599 |
+
"""
|
600 |
+
cetree.setNodeText(self._c_node, s)
|
601 |
+
|
602 |
+
|
603 |
+
cdef class NumberElement(ObjectifiedDataElement):
|
604 |
+
cdef object _parse_value
|
605 |
+
|
606 |
+
def _setValueParser(self, function):
|
607 |
+
"""Set the function that parses the Python value from a string.
|
608 |
+
|
609 |
+
Do not use this unless you know what you are doing.
|
610 |
+
"""
|
611 |
+
self._parse_value = function
|
612 |
+
|
613 |
+
@property
|
614 |
+
def pyval(self):
|
615 |
+
return _parseNumber(self)
|
616 |
+
|
617 |
+
def __int__(self):
|
618 |
+
return int(_parseNumber(self))
|
619 |
+
|
620 |
+
def __float__(self):
|
621 |
+
return float(_parseNumber(self))
|
622 |
+
|
623 |
+
def __complex__(self):
|
624 |
+
return complex(_parseNumber(self))
|
625 |
+
|
626 |
+
def __str__(self):
|
627 |
+
return unicode(_parseNumber(self))
|
628 |
+
|
629 |
+
def __repr__(self):
|
630 |
+
return repr(_parseNumber(self))
|
631 |
+
|
632 |
+
def __oct__(self):
|
633 |
+
return oct(_parseNumber(self))
|
634 |
+
|
635 |
+
def __hex__(self):
|
636 |
+
return hex(_parseNumber(self))
|
637 |
+
|
638 |
+
def __richcmp__(self, other, int op):
|
639 |
+
return _richcmpPyvals(self, other, op)
|
640 |
+
|
641 |
+
def __hash__(self):
|
642 |
+
return hash(_parseNumber(self))
|
643 |
+
|
644 |
+
def __add__(self, other):
|
645 |
+
return _numericValueOf(self) + _numericValueOf(other)
|
646 |
+
|
647 |
+
def __radd__(self, other):
|
648 |
+
return _numericValueOf(other) + _numericValueOf(self)
|
649 |
+
|
650 |
+
def __sub__(self, other):
|
651 |
+
return _numericValueOf(self) - _numericValueOf(other)
|
652 |
+
|
653 |
+
def __rsub__(self, other):
|
654 |
+
return _numericValueOf(other) - _numericValueOf(self)
|
655 |
+
|
656 |
+
def __mul__(self, other):
|
657 |
+
return _numericValueOf(self) * _numericValueOf(other)
|
658 |
+
|
659 |
+
def __rmul__(self, other):
|
660 |
+
return _numericValueOf(other) * _numericValueOf(self)
|
661 |
+
|
662 |
+
def __div__(self, other):
|
663 |
+
return _numericValueOf(self) / _numericValueOf(other)
|
664 |
+
|
665 |
+
def __rdiv__(self, other):
|
666 |
+
return _numericValueOf(other) / _numericValueOf(self)
|
667 |
+
|
668 |
+
def __truediv__(self, other):
|
669 |
+
return _numericValueOf(self) / _numericValueOf(other)
|
670 |
+
|
671 |
+
def __rtruediv__(self, other):
|
672 |
+
return _numericValueOf(other) / _numericValueOf(self)
|
673 |
+
|
674 |
+
def __floordiv__(self, other):
|
675 |
+
return _numericValueOf(self) // _numericValueOf(other)
|
676 |
+
|
677 |
+
def __rfloordiv__(self, other):
|
678 |
+
return _numericValueOf(other) // _numericValueOf(self)
|
679 |
+
|
680 |
+
def __mod__(self, other):
|
681 |
+
return _numericValueOf(self) % _numericValueOf(other)
|
682 |
+
|
683 |
+
def __rmod__(self, other):
|
684 |
+
return _numericValueOf(other) % _numericValueOf(self)
|
685 |
+
|
686 |
+
def __divmod__(self, other):
|
687 |
+
return divmod(_numericValueOf(self), _numericValueOf(other))
|
688 |
+
|
689 |
+
def __rdivmod__(self, other):
|
690 |
+
return divmod(_numericValueOf(other), _numericValueOf(self))
|
691 |
+
|
692 |
+
def __pow__(self, other, modulo):
|
693 |
+
if modulo is None:
|
694 |
+
return _numericValueOf(self) ** _numericValueOf(other)
|
695 |
+
else:
|
696 |
+
return pow(_numericValueOf(self), _numericValueOf(other), modulo)
|
697 |
+
|
698 |
+
def __rpow__(self, other, modulo):
|
699 |
+
if modulo is None:
|
700 |
+
return _numericValueOf(other) ** _numericValueOf(self)
|
701 |
+
else:
|
702 |
+
return pow(_numericValueOf(other), _numericValueOf(self), modulo)
|
703 |
+
|
704 |
+
def __neg__(self):
|
705 |
+
return - _numericValueOf(self)
|
706 |
+
|
707 |
+
def __pos__(self):
|
708 |
+
return + _numericValueOf(self)
|
709 |
+
|
710 |
+
def __abs__(self):
|
711 |
+
return abs( _numericValueOf(self) )
|
712 |
+
|
713 |
+
def __bool__(self):
|
714 |
+
return bool(_numericValueOf(self))
|
715 |
+
|
716 |
+
def __invert__(self):
|
717 |
+
return ~ _numericValueOf(self)
|
718 |
+
|
719 |
+
def __lshift__(self, other):
|
720 |
+
return _numericValueOf(self) << _numericValueOf(other)
|
721 |
+
|
722 |
+
def __rlshift__(self, other):
|
723 |
+
return _numericValueOf(other) << _numericValueOf(self)
|
724 |
+
|
725 |
+
def __rshift__(self, other):
|
726 |
+
return _numericValueOf(self) >> _numericValueOf(other)
|
727 |
+
|
728 |
+
def __rrshift__(self, other):
|
729 |
+
return _numericValueOf(other) >> _numericValueOf(self)
|
730 |
+
|
731 |
+
def __and__(self, other):
|
732 |
+
return _numericValueOf(self) & _numericValueOf(other)
|
733 |
+
|
734 |
+
def __rand__(self, other):
|
735 |
+
return _numericValueOf(other) & _numericValueOf(self)
|
736 |
+
|
737 |
+
def __or__(self, other):
|
738 |
+
return _numericValueOf(self) | _numericValueOf(other)
|
739 |
+
|
740 |
+
def __ror__(self, other):
|
741 |
+
return _numericValueOf(other) | _numericValueOf(self)
|
742 |
+
|
743 |
+
def __xor__(self, other):
|
744 |
+
return _numericValueOf(self) ^ _numericValueOf(other)
|
745 |
+
|
746 |
+
def __rxor__(self, other):
|
747 |
+
return _numericValueOf(other) ^ _numericValueOf(self)
|
748 |
+
|
749 |
+
|
750 |
+
cdef class IntElement(NumberElement):
|
751 |
+
def _init(self):
|
752 |
+
self._parse_value = int
|
753 |
+
|
754 |
+
def __index__(self):
|
755 |
+
return int(_parseNumber(self))
|
756 |
+
|
757 |
+
|
758 |
+
cdef class FloatElement(NumberElement):
|
759 |
+
def _init(self):
|
760 |
+
self._parse_value = float
|
761 |
+
|
762 |
+
|
763 |
+
cdef class StringElement(ObjectifiedDataElement):
|
764 |
+
"""String data class.
|
765 |
+
|
766 |
+
Note that this class does *not* support the sequence protocol of strings:
|
767 |
+
len(), iter(), str_attr[0], str_attr[0:1], etc. are *not* supported.
|
768 |
+
Instead, use the .text attribute to get a 'real' string.
|
769 |
+
"""
|
770 |
+
@property
|
771 |
+
def pyval(self):
|
772 |
+
return textOf(self._c_node) or ''
|
773 |
+
|
774 |
+
def __repr__(self):
|
775 |
+
return repr(textOf(self._c_node) or '')
|
776 |
+
|
777 |
+
def strlen(self):
|
778 |
+
text = textOf(self._c_node)
|
779 |
+
if text is None:
|
780 |
+
return 0
|
781 |
+
else:
|
782 |
+
return len(text)
|
783 |
+
|
784 |
+
def __bool__(self):
|
785 |
+
return bool(textOf(self._c_node))
|
786 |
+
|
787 |
+
def __richcmp__(self, other, int op):
|
788 |
+
return _richcmpPyvals(self, other, op)
|
789 |
+
|
790 |
+
def __hash__(self):
|
791 |
+
return hash(textOf(self._c_node) or '')
|
792 |
+
|
793 |
+
def __add__(self, other):
|
794 |
+
text = _strValueOf(self)
|
795 |
+
other = _strValueOf(other)
|
796 |
+
return text + other
|
797 |
+
|
798 |
+
def __radd__(self, other):
|
799 |
+
text = _strValueOf(self)
|
800 |
+
other = _strValueOf(other)
|
801 |
+
return other + text
|
802 |
+
|
803 |
+
def __mul__(self, other):
|
804 |
+
if isinstance(self, StringElement):
|
805 |
+
return (textOf((<StringElement>self)._c_node) or '') * _numericValueOf(other)
|
806 |
+
elif isinstance(other, StringElement):
|
807 |
+
return _numericValueOf(self) * (textOf((<StringElement>other)._c_node) or '')
|
808 |
+
else:
|
809 |
+
return NotImplemented
|
810 |
+
|
811 |
+
def __rmul__(self, other):
|
812 |
+
return _numericValueOf(other) * (textOf((<StringElement>self)._c_node) or '')
|
813 |
+
|
814 |
+
def __mod__(self, other):
|
815 |
+
return (_strValueOf(self) or '') % other
|
816 |
+
|
817 |
+
def __int__(self):
|
818 |
+
return int(textOf(self._c_node))
|
819 |
+
|
820 |
+
def __float__(self):
|
821 |
+
return float(textOf(self._c_node))
|
822 |
+
|
823 |
+
def __complex__(self):
|
824 |
+
return complex(textOf(self._c_node))
|
825 |
+
|
826 |
+
|
827 |
+
cdef class NoneElement(ObjectifiedDataElement):
|
828 |
+
def __str__(self):
|
829 |
+
return "None"
|
830 |
+
|
831 |
+
def __repr__(self):
|
832 |
+
return "None"
|
833 |
+
|
834 |
+
def __bool__(self):
|
835 |
+
return False
|
836 |
+
|
837 |
+
def __richcmp__(self, other, int op):
|
838 |
+
if other is None or self is None:
|
839 |
+
return python.PyObject_RichCompare(None, None, op)
|
840 |
+
if isinstance(self, NoneElement):
|
841 |
+
return python.PyObject_RichCompare(None, other, op)
|
842 |
+
else:
|
843 |
+
return python.PyObject_RichCompare(self, None, op)
|
844 |
+
|
845 |
+
def __hash__(self):
|
846 |
+
return hash(None)
|
847 |
+
|
848 |
+
@property
|
849 |
+
def pyval(self):
|
850 |
+
return None
|
851 |
+
|
852 |
+
|
853 |
+
cdef class BoolElement(IntElement):
|
854 |
+
"""Boolean type base on string values: 'true' or 'false'.
|
855 |
+
|
856 |
+
Note that this inherits from IntElement to mimic the behaviour of
|
857 |
+
Python's bool type.
|
858 |
+
"""
|
859 |
+
def _init(self):
|
860 |
+
self._parse_value = _parseBool # wraps as Python callable
|
861 |
+
|
862 |
+
def __bool__(self):
|
863 |
+
return _parseBool(textOf(self._c_node))
|
864 |
+
|
865 |
+
def __int__(self):
|
866 |
+
return 0 + _parseBool(textOf(self._c_node))
|
867 |
+
|
868 |
+
def __float__(self):
|
869 |
+
return 0.0 + _parseBool(textOf(self._c_node))
|
870 |
+
|
871 |
+
def __richcmp__(self, other, int op):
|
872 |
+
return _richcmpPyvals(self, other, op)
|
873 |
+
|
874 |
+
def __hash__(self):
|
875 |
+
return hash(_parseBool(textOf(self._c_node)))
|
876 |
+
|
877 |
+
def __str__(self):
|
878 |
+
return unicode(_parseBool(textOf(self._c_node)))
|
879 |
+
|
880 |
+
def __repr__(self):
|
881 |
+
return repr(_parseBool(textOf(self._c_node)))
|
882 |
+
|
883 |
+
@property
|
884 |
+
def pyval(self):
|
885 |
+
return _parseBool(textOf(self._c_node))
|
886 |
+
|
887 |
+
|
888 |
+
cdef _checkBool(s):
|
889 |
+
cdef int value = -1
|
890 |
+
if s is not None:
|
891 |
+
value = __parseBoolAsInt(s)
|
892 |
+
if value == -1:
|
893 |
+
raise ValueError
|
894 |
+
|
895 |
+
|
896 |
+
cdef bint _parseBool(s) except -1:
|
897 |
+
cdef int value
|
898 |
+
if s is None:
|
899 |
+
return False
|
900 |
+
value = __parseBoolAsInt(s)
|
901 |
+
if value == -1:
|
902 |
+
raise ValueError, f"Invalid boolean value: '{s}'"
|
903 |
+
return value
|
904 |
+
|
905 |
+
|
906 |
+
cdef inline int __parseBoolAsInt(text) except -2:
|
907 |
+
if text == 'false':
|
908 |
+
return 0
|
909 |
+
elif text == 'true':
|
910 |
+
return 1
|
911 |
+
elif text == '0':
|
912 |
+
return 0
|
913 |
+
elif text == '1':
|
914 |
+
return 1
|
915 |
+
return -1
|
916 |
+
|
917 |
+
|
918 |
+
cdef object _parseNumber(NumberElement element):
|
919 |
+
return element._parse_value(textOf(element._c_node))
|
920 |
+
|
921 |
+
|
922 |
+
cdef enum NumberParserState:
|
923 |
+
NPS_SPACE_PRE = 0
|
924 |
+
NPS_SIGN = 1
|
925 |
+
NPS_DIGITS = 2
|
926 |
+
NPS_POINT_LEAD = 3
|
927 |
+
NPS_POINT = 4
|
928 |
+
NPS_FRACTION = 5
|
929 |
+
NPS_EXP = 6
|
930 |
+
NPS_EXP_SIGN = 7
|
931 |
+
NPS_DIGITS_EXP = 8
|
932 |
+
NPS_SPACE_TAIL = 9
|
933 |
+
NPS_INF1 = 20
|
934 |
+
NPS_INF2 = 21
|
935 |
+
NPS_INF3 = 22
|
936 |
+
NPS_NAN1 = 23
|
937 |
+
NPS_NAN2 = 24
|
938 |
+
NPS_NAN3 = 25
|
939 |
+
NPS_ERROR = 99
|
940 |
+
|
941 |
+
|
942 |
+
ctypedef fused bytes_unicode:
|
943 |
+
bytes
|
944 |
+
unicode
|
945 |
+
|
946 |
+
|
947 |
+
cdef _checkNumber(bytes_unicode s, bint allow_float):
|
948 |
+
cdef Py_UCS4 c
|
949 |
+
cdef NumberParserState state = NPS_SPACE_PRE
|
950 |
+
|
951 |
+
for c in s:
|
952 |
+
if c in '0123456789':
|
953 |
+
if state in (NPS_DIGITS, NPS_FRACTION, NPS_DIGITS_EXP):
|
954 |
+
pass
|
955 |
+
elif state in (NPS_SPACE_PRE, NPS_SIGN):
|
956 |
+
state = NPS_DIGITS
|
957 |
+
elif state in (NPS_POINT_LEAD, NPS_POINT):
|
958 |
+
state = NPS_FRACTION
|
959 |
+
elif state in (NPS_EXP, NPS_EXP_SIGN):
|
960 |
+
state = NPS_DIGITS_EXP
|
961 |
+
else:
|
962 |
+
state = NPS_ERROR
|
963 |
+
else:
|
964 |
+
if c == '.':
|
965 |
+
if state in (NPS_SPACE_PRE, NPS_SIGN):
|
966 |
+
state = NPS_POINT_LEAD
|
967 |
+
elif state == NPS_DIGITS:
|
968 |
+
state = NPS_POINT
|
969 |
+
else:
|
970 |
+
state = NPS_ERROR
|
971 |
+
if not allow_float:
|
972 |
+
state = NPS_ERROR
|
973 |
+
elif c in '-+':
|
974 |
+
if state == NPS_SPACE_PRE:
|
975 |
+
state = NPS_SIGN
|
976 |
+
elif state == NPS_EXP:
|
977 |
+
state = NPS_EXP_SIGN
|
978 |
+
else:
|
979 |
+
state = NPS_ERROR
|
980 |
+
elif c == 'E':
|
981 |
+
if state in (NPS_DIGITS, NPS_POINT, NPS_FRACTION):
|
982 |
+
state = NPS_EXP
|
983 |
+
else:
|
984 |
+
state = NPS_ERROR
|
985 |
+
if not allow_float:
|
986 |
+
state = NPS_ERROR
|
987 |
+
# Allow INF and NaN. XMLSchema requires case, we don't, like Python.
|
988 |
+
elif c in 'iI':
|
989 |
+
state = NPS_INF1 if allow_float and state in (NPS_SPACE_PRE, NPS_SIGN) else NPS_ERROR
|
990 |
+
elif c in 'fF':
|
991 |
+
state = NPS_INF3 if state == NPS_INF2 else NPS_ERROR
|
992 |
+
elif c in 'aA':
|
993 |
+
state = NPS_NAN2 if state == NPS_NAN1 else NPS_ERROR
|
994 |
+
elif c in 'nN':
|
995 |
+
# Python also allows [+-]NaN, so let's accept that.
|
996 |
+
if state in (NPS_SPACE_PRE, NPS_SIGN):
|
997 |
+
state = NPS_NAN1 if allow_float else NPS_ERROR
|
998 |
+
elif state == NPS_NAN2:
|
999 |
+
state = NPS_NAN3
|
1000 |
+
elif state == NPS_INF1:
|
1001 |
+
state = NPS_INF2
|
1002 |
+
else:
|
1003 |
+
state = NPS_ERROR
|
1004 |
+
# Allow spaces around text values.
|
1005 |
+
else:
|
1006 |
+
if c.isspace() if (bytes_unicode is unicode) else c in b'\x09\x0a\x0b\x0c\x0d\x20':
|
1007 |
+
if state in (NPS_SPACE_PRE, NPS_SPACE_TAIL):
|
1008 |
+
pass
|
1009 |
+
elif state in (NPS_DIGITS, NPS_POINT, NPS_FRACTION, NPS_DIGITS_EXP, NPS_INF3, NPS_NAN3):
|
1010 |
+
state = NPS_SPACE_TAIL
|
1011 |
+
else:
|
1012 |
+
state = NPS_ERROR
|
1013 |
+
else:
|
1014 |
+
state = NPS_ERROR
|
1015 |
+
|
1016 |
+
if state == NPS_ERROR:
|
1017 |
+
break
|
1018 |
+
|
1019 |
+
if state not in (NPS_DIGITS, NPS_FRACTION, NPS_POINT, NPS_DIGITS_EXP, NPS_INF3, NPS_NAN3, NPS_SPACE_TAIL):
|
1020 |
+
raise ValueError
|
1021 |
+
|
1022 |
+
|
1023 |
+
cdef _checkInt(s):
|
1024 |
+
return _checkNumber(<unicode>s, allow_float=False)
|
1025 |
+
|
1026 |
+
|
1027 |
+
cdef _checkFloat(s):
|
1028 |
+
return _checkNumber(<unicode>s, allow_float=True)
|
1029 |
+
|
1030 |
+
|
1031 |
+
cdef object _strValueOf(obj):
|
1032 |
+
if python._isString(obj):
|
1033 |
+
return obj
|
1034 |
+
if isinstance(obj, _Element):
|
1035 |
+
return textOf((<_Element>obj)._c_node) or ''
|
1036 |
+
if obj is None:
|
1037 |
+
return ''
|
1038 |
+
return unicode(obj)
|
1039 |
+
|
1040 |
+
|
1041 |
+
cdef object _numericValueOf(obj):
|
1042 |
+
if isinstance(obj, NumberElement):
|
1043 |
+
return _parseNumber(<NumberElement>obj)
|
1044 |
+
try:
|
1045 |
+
# not always numeric, but Python will raise the right exception
|
1046 |
+
return obj.pyval
|
1047 |
+
except AttributeError:
|
1048 |
+
pass
|
1049 |
+
return obj
|
1050 |
+
|
1051 |
+
|
1052 |
+
cdef _richcmpPyvals(left, right, int op):
|
1053 |
+
left = getattr(left, 'pyval', left)
|
1054 |
+
right = getattr(right, 'pyval', right)
|
1055 |
+
return python.PyObject_RichCompare(left, right, op)
|
1056 |
+
|
1057 |
+
|
1058 |
+
################################################################################
|
1059 |
+
# Python type registry
|
1060 |
+
|
1061 |
+
cdef class PyType:
|
1062 |
+
"""PyType(self, name, type_check, type_class, stringify=None)
|
1063 |
+
User defined type.
|
1064 |
+
|
1065 |
+
Named type that contains a type check function, a type class that
|
1066 |
+
inherits from ObjectifiedDataElement and an optional "stringification"
|
1067 |
+
function. The type check must take a string as argument and raise
|
1068 |
+
ValueError or TypeError if it cannot handle the string value. It may be
|
1069 |
+
None in which case it is not considered for type guessing. For registered
|
1070 |
+
named types, the 'stringify' function (or unicode() if None) is used to
|
1071 |
+
convert a Python object with type name 'name' to the string representation
|
1072 |
+
stored in the XML tree.
|
1073 |
+
|
1074 |
+
Example::
|
1075 |
+
|
1076 |
+
PyType('int', int, MyIntClass).register()
|
1077 |
+
|
1078 |
+
Note that the order in which types are registered matters. The first
|
1079 |
+
matching type will be used.
|
1080 |
+
"""
|
1081 |
+
cdef readonly object name
|
1082 |
+
cdef readonly object type_check
|
1083 |
+
cdef readonly object stringify
|
1084 |
+
cdef object _type
|
1085 |
+
cdef list _schema_types
|
1086 |
+
def __init__(self, name, type_check, type_class, stringify=None):
|
1087 |
+
if isinstance(name, bytes):
|
1088 |
+
name = (<bytes>name).decode('ascii')
|
1089 |
+
elif not isinstance(name, unicode):
|
1090 |
+
raise TypeError, "Type name must be a string"
|
1091 |
+
if type_check is not None and not callable(type_check):
|
1092 |
+
raise TypeError, "Type check function must be callable (or None)"
|
1093 |
+
if name != TREE_PYTYPE_NAME and \
|
1094 |
+
not issubclass(type_class, ObjectifiedDataElement):
|
1095 |
+
raise TypeError, \
|
1096 |
+
"Data classes must inherit from ObjectifiedDataElement"
|
1097 |
+
self.name = name
|
1098 |
+
self._type = type_class
|
1099 |
+
self.type_check = type_check
|
1100 |
+
if stringify is None:
|
1101 |
+
stringify = unicode
|
1102 |
+
self.stringify = stringify
|
1103 |
+
self._schema_types = []
|
1104 |
+
|
1105 |
+
def __repr__(self):
|
1106 |
+
return "PyType(%s, %s)" % (self.name, self._type.__name__)
|
1107 |
+
|
1108 |
+
def register(self, before=None, after=None):
|
1109 |
+
"""register(self, before=None, after=None)
|
1110 |
+
|
1111 |
+
Register the type.
|
1112 |
+
|
1113 |
+
The additional keyword arguments 'before' and 'after' accept a
|
1114 |
+
sequence of type names that must appear before/after the new type in
|
1115 |
+
the type list. If any of them is not currently known, it is simply
|
1116 |
+
ignored. Raises ValueError if the dependencies cannot be fulfilled.
|
1117 |
+
"""
|
1118 |
+
if self.name == TREE_PYTYPE_NAME:
|
1119 |
+
raise ValueError, "Cannot register tree type"
|
1120 |
+
if self.type_check is not None:
|
1121 |
+
for item in _TYPE_CHECKS:
|
1122 |
+
if item[0] is self.type_check:
|
1123 |
+
_TYPE_CHECKS.remove(item)
|
1124 |
+
break
|
1125 |
+
entry = (self.type_check, self)
|
1126 |
+
first_pos = 0
|
1127 |
+
last_pos = -1
|
1128 |
+
if before or after:
|
1129 |
+
if before is None:
|
1130 |
+
before = ()
|
1131 |
+
elif after is None:
|
1132 |
+
after = ()
|
1133 |
+
for i, (check, pytype) in enumerate(_TYPE_CHECKS):
|
1134 |
+
if last_pos == -1 and pytype.name in before:
|
1135 |
+
last_pos = i
|
1136 |
+
if pytype.name in after:
|
1137 |
+
first_pos = i+1
|
1138 |
+
if last_pos == -1:
|
1139 |
+
_TYPE_CHECKS.append(entry)
|
1140 |
+
elif first_pos > last_pos:
|
1141 |
+
raise ValueError, "inconsistent before/after dependencies"
|
1142 |
+
else:
|
1143 |
+
_TYPE_CHECKS.insert(last_pos, entry)
|
1144 |
+
|
1145 |
+
_PYTYPE_DICT[self.name] = self
|
1146 |
+
for xs_type in self._schema_types:
|
1147 |
+
_SCHEMA_TYPE_DICT[xs_type] = self
|
1148 |
+
|
1149 |
+
def unregister(self):
|
1150 |
+
"unregister(self)"
|
1151 |
+
if _PYTYPE_DICT.get(self.name) is self:
|
1152 |
+
del _PYTYPE_DICT[self.name]
|
1153 |
+
for xs_type, pytype in list(_SCHEMA_TYPE_DICT.items()):
|
1154 |
+
if pytype is self:
|
1155 |
+
del _SCHEMA_TYPE_DICT[xs_type]
|
1156 |
+
if self.type_check is None:
|
1157 |
+
return
|
1158 |
+
try:
|
1159 |
+
_TYPE_CHECKS.remove( (self.type_check, self) )
|
1160 |
+
except ValueError:
|
1161 |
+
pass
|
1162 |
+
|
1163 |
+
property xmlSchemaTypes:
|
1164 |
+
"""The list of XML Schema datatypes this Python type maps to.
|
1165 |
+
|
1166 |
+
Note that this must be set before registering the type!
|
1167 |
+
"""
|
1168 |
+
def __get__(self):
|
1169 |
+
return self._schema_types
|
1170 |
+
def __set__(self, types):
|
1171 |
+
self._schema_types = list(map(unicode, types))
|
1172 |
+
|
1173 |
+
|
1174 |
+
cdef dict _PYTYPE_DICT = {}
|
1175 |
+
cdef dict _SCHEMA_TYPE_DICT = {}
|
1176 |
+
cdef list _TYPE_CHECKS = []
|
1177 |
+
|
1178 |
+
cdef unicode _xml_bool(value):
|
1179 |
+
return "true" if value else "false"
|
1180 |
+
|
1181 |
+
cdef unicode _xml_float(value):
|
1182 |
+
if _float_is_inf(value):
|
1183 |
+
if value > 0:
|
1184 |
+
return "INF"
|
1185 |
+
return "-INF"
|
1186 |
+
if _float_is_nan(value):
|
1187 |
+
return "NaN"
|
1188 |
+
return unicode(repr(value))
|
1189 |
+
|
1190 |
+
cdef _pytypename(obj):
|
1191 |
+
return "str" if python._isString(obj) else _typename(obj)
|
1192 |
+
|
1193 |
+
def pytypename(obj):
|
1194 |
+
"""pytypename(obj)
|
1195 |
+
|
1196 |
+
Find the name of the corresponding PyType for a Python object.
|
1197 |
+
"""
|
1198 |
+
return _pytypename(obj)
|
1199 |
+
|
1200 |
+
cdef _registerPyTypes():
|
1201 |
+
pytype = PyType('int', _checkInt, IntElement) # wraps functions for Python
|
1202 |
+
pytype.xmlSchemaTypes = ("integer", "int", "short", "byte", "unsignedShort",
|
1203 |
+
"unsignedByte", "nonPositiveInteger",
|
1204 |
+
"negativeInteger", "long", "nonNegativeInteger",
|
1205 |
+
"unsignedLong", "unsignedInt", "positiveInteger",)
|
1206 |
+
pytype.register()
|
1207 |
+
|
1208 |
+
# 'long' type just for backwards compatibility
|
1209 |
+
pytype = PyType('long', None, IntElement)
|
1210 |
+
pytype.register()
|
1211 |
+
|
1212 |
+
pytype = PyType('float', _checkFloat, FloatElement, _xml_float) # wraps functions for Python
|
1213 |
+
pytype.xmlSchemaTypes = ("double", "float")
|
1214 |
+
pytype.register()
|
1215 |
+
|
1216 |
+
pytype = PyType('bool', _checkBool, BoolElement, _xml_bool) # wraps functions for Python
|
1217 |
+
pytype.xmlSchemaTypes = ("boolean",)
|
1218 |
+
pytype.register()
|
1219 |
+
|
1220 |
+
pytype = PyType('str', None, StringElement)
|
1221 |
+
pytype.xmlSchemaTypes = ("string", "normalizedString", "token", "language",
|
1222 |
+
"Name", "NCName", "ID", "IDREF", "ENTITY",
|
1223 |
+
"NMTOKEN", )
|
1224 |
+
pytype.register()
|
1225 |
+
|
1226 |
+
# since lxml 2.0
|
1227 |
+
pytype = PyType('NoneType', None, NoneElement)
|
1228 |
+
pytype.register()
|
1229 |
+
|
1230 |
+
# backwards compatibility
|
1231 |
+
pytype = PyType('none', None, NoneElement)
|
1232 |
+
pytype.register()
|
1233 |
+
|
1234 |
+
# non-registered PyType for inner tree elements
|
1235 |
+
cdef PyType TREE_PYTYPE = PyType(TREE_PYTYPE_NAME, None, ObjectifiedElement)
|
1236 |
+
|
1237 |
+
_registerPyTypes()
|
1238 |
+
|
1239 |
+
def getRegisteredTypes():
|
1240 |
+
"""getRegisteredTypes()
|
1241 |
+
|
1242 |
+
Returns a list of the currently registered PyType objects.
|
1243 |
+
|
1244 |
+
To add a new type, retrieve this list and call unregister() for all
|
1245 |
+
entries. Then add the new type at a suitable position (possibly replacing
|
1246 |
+
an existing one) and call register() for all entries.
|
1247 |
+
|
1248 |
+
This is necessary if the new type interferes with the type check functions
|
1249 |
+
of existing ones (normally only int/float/bool) and must the tried before
|
1250 |
+
other types. To add a type that is not yet parsable by the current type
|
1251 |
+
check functions, you can simply register() it, which will append it to the
|
1252 |
+
end of the type list.
|
1253 |
+
"""
|
1254 |
+
cdef list types = []
|
1255 |
+
cdef set known = set()
|
1256 |
+
for check, pytype in _TYPE_CHECKS:
|
1257 |
+
name = pytype.name
|
1258 |
+
if name not in known:
|
1259 |
+
known.add(name)
|
1260 |
+
types.append(pytype)
|
1261 |
+
for pytype in _PYTYPE_DICT.values():
|
1262 |
+
name = pytype.name
|
1263 |
+
if name not in known:
|
1264 |
+
known.add(name)
|
1265 |
+
types.append(pytype)
|
1266 |
+
return types
|
1267 |
+
|
1268 |
+
cdef PyType _guessPyType(value, PyType defaulttype):
|
1269 |
+
if value is None:
|
1270 |
+
return None
|
1271 |
+
for type_check, tested_pytype in _TYPE_CHECKS:
|
1272 |
+
try:
|
1273 |
+
type_check(value)
|
1274 |
+
return <PyType>tested_pytype
|
1275 |
+
except IGNORABLE_ERRORS:
|
1276 |
+
# could not be parsed as the specified type => ignore
|
1277 |
+
pass
|
1278 |
+
return defaulttype
|
1279 |
+
|
1280 |
+
cdef object _guessElementClass(tree.xmlNode* c_node):
|
1281 |
+
value = textOf(c_node)
|
1282 |
+
if value is None:
|
1283 |
+
return None
|
1284 |
+
if value == '':
|
1285 |
+
return StringElement
|
1286 |
+
|
1287 |
+
for type_check, pytype in _TYPE_CHECKS:
|
1288 |
+
try:
|
1289 |
+
type_check(value)
|
1290 |
+
return (<PyType>pytype)._type
|
1291 |
+
except IGNORABLE_ERRORS:
|
1292 |
+
pass
|
1293 |
+
return None
|
1294 |
+
|
1295 |
+
################################################################################
|
1296 |
+
# adapted ElementMaker supports registered PyTypes
|
1297 |
+
|
1298 |
+
@cython.final
|
1299 |
+
@cython.internal
|
1300 |
+
cdef class _ObjectifyElementMakerCaller:
|
1301 |
+
cdef object _tag
|
1302 |
+
cdef object _nsmap
|
1303 |
+
cdef object _element_factory
|
1304 |
+
cdef bint _annotate
|
1305 |
+
|
1306 |
+
def __call__(self, *children, **attrib):
|
1307 |
+
"__call__(self, *children, **attrib)"
|
1308 |
+
cdef _ObjectifyElementMakerCaller elementMaker
|
1309 |
+
cdef _Element element
|
1310 |
+
cdef _Element childElement
|
1311 |
+
cdef bint has_children
|
1312 |
+
cdef bint has_string_value
|
1313 |
+
if self._element_factory is None:
|
1314 |
+
element = _makeElement(self._tag, None, attrib, self._nsmap)
|
1315 |
+
else:
|
1316 |
+
element = self._element_factory(self._tag, attrib, self._nsmap)
|
1317 |
+
|
1318 |
+
pytype_name = None
|
1319 |
+
has_children = False
|
1320 |
+
has_string_value = False
|
1321 |
+
for child in children:
|
1322 |
+
if child is None:
|
1323 |
+
if len(children) == 1:
|
1324 |
+
cetree.setAttributeValue(
|
1325 |
+
element, XML_SCHEMA_INSTANCE_NIL_ATTR, "true")
|
1326 |
+
elif python._isString(child):
|
1327 |
+
_add_text(element, child)
|
1328 |
+
has_string_value = True
|
1329 |
+
elif isinstance(child, _Element):
|
1330 |
+
cetree.appendChildToElement(element, <_Element>child)
|
1331 |
+
has_children = True
|
1332 |
+
elif isinstance(child, _ObjectifyElementMakerCaller):
|
1333 |
+
elementMaker = <_ObjectifyElementMakerCaller>child
|
1334 |
+
if elementMaker._element_factory is None:
|
1335 |
+
cetree.makeSubElement(element, elementMaker._tag,
|
1336 |
+
None, None, None, None)
|
1337 |
+
else:
|
1338 |
+
childElement = elementMaker._element_factory(
|
1339 |
+
elementMaker._tag)
|
1340 |
+
cetree.appendChildToElement(element, childElement)
|
1341 |
+
has_children = True
|
1342 |
+
elif isinstance(child, dict):
|
1343 |
+
for name, value in child.items():
|
1344 |
+
# keyword arguments in attrib take precedence
|
1345 |
+
if name in attrib:
|
1346 |
+
continue
|
1347 |
+
pytype = _PYTYPE_DICT.get(_typename(value))
|
1348 |
+
if pytype is not None:
|
1349 |
+
value = (<PyType>pytype).stringify(value)
|
1350 |
+
elif not python._isString(value):
|
1351 |
+
value = unicode(value)
|
1352 |
+
cetree.setAttributeValue(element, name, value)
|
1353 |
+
else:
|
1354 |
+
if pytype_name is not None:
|
1355 |
+
# concatenation always makes the result a string
|
1356 |
+
has_string_value = True
|
1357 |
+
pytype_name = _typename(child)
|
1358 |
+
pytype = _PYTYPE_DICT.get(_typename(child))
|
1359 |
+
if pytype is not None:
|
1360 |
+
_add_text(element, (<PyType>pytype).stringify(child))
|
1361 |
+
else:
|
1362 |
+
has_string_value = True
|
1363 |
+
child = unicode(child)
|
1364 |
+
_add_text(element, child)
|
1365 |
+
|
1366 |
+
if self._annotate and not has_children:
|
1367 |
+
if has_string_value:
|
1368 |
+
cetree.setAttributeValue(element, PYTYPE_ATTRIBUTE, "str")
|
1369 |
+
elif pytype_name is not None:
|
1370 |
+
cetree.setAttributeValue(element, PYTYPE_ATTRIBUTE, pytype_name)
|
1371 |
+
|
1372 |
+
return element
|
1373 |
+
|
1374 |
+
cdef _add_text(_Element elem, text):
|
1375 |
+
# add text to the tree in construction, either as element text or
|
1376 |
+
# tail text, depending on the current tree state
|
1377 |
+
cdef tree.xmlNode* c_child
|
1378 |
+
c_child = cetree.findChildBackwards(elem._c_node, 0)
|
1379 |
+
if c_child is not NULL:
|
1380 |
+
old = cetree.tailOf(c_child)
|
1381 |
+
if old is not None:
|
1382 |
+
text = old + text
|
1383 |
+
cetree.setTailText(c_child, text)
|
1384 |
+
else:
|
1385 |
+
old = cetree.textOf(elem._c_node)
|
1386 |
+
if old is not None:
|
1387 |
+
text = old + text
|
1388 |
+
cetree.setNodeText(elem._c_node, text)
|
1389 |
+
|
1390 |
+
cdef class ElementMaker:
|
1391 |
+
"""ElementMaker(self, namespace=None, nsmap=None, annotate=True, makeelement=None)
|
1392 |
+
|
1393 |
+
An ElementMaker that can be used for constructing trees.
|
1394 |
+
|
1395 |
+
Example::
|
1396 |
+
|
1397 |
+
>>> M = ElementMaker(annotate=False)
|
1398 |
+
>>> attributes = {'class': 'par'}
|
1399 |
+
>>> html = M.html( M.body( M.p('hello', attributes, M.br, 'objectify', style="font-weight: bold") ) )
|
1400 |
+
|
1401 |
+
>>> from lxml.etree import tostring
|
1402 |
+
>>> print(tostring(html, method='html').decode('ascii'))
|
1403 |
+
<html><body><p style="font-weight: bold" class="par">hello<br>objectify</p></body></html>
|
1404 |
+
|
1405 |
+
To create tags that are not valid Python identifiers, call the factory
|
1406 |
+
directly and pass the tag name as first argument::
|
1407 |
+
|
1408 |
+
>>> root = M('tricky-tag', 'some text')
|
1409 |
+
>>> print(root.tag)
|
1410 |
+
tricky-tag
|
1411 |
+
>>> print(root.text)
|
1412 |
+
some text
|
1413 |
+
|
1414 |
+
Note that this module has a predefined ElementMaker instance called ``E``.
|
1415 |
+
"""
|
1416 |
+
cdef object _makeelement
|
1417 |
+
cdef object _namespace
|
1418 |
+
cdef object _nsmap
|
1419 |
+
cdef bint _annotate
|
1420 |
+
cdef dict _cache
|
1421 |
+
def __init__(self, *, namespace=None, nsmap=None, annotate=True,
|
1422 |
+
makeelement=None):
|
1423 |
+
if nsmap is None:
|
1424 |
+
nsmap = _DEFAULT_NSMAP if annotate else {}
|
1425 |
+
self._nsmap = nsmap
|
1426 |
+
self._namespace = None if namespace is None else "{%s}" % namespace
|
1427 |
+
self._annotate = annotate
|
1428 |
+
if makeelement is not None:
|
1429 |
+
if not callable(makeelement):
|
1430 |
+
raise TypeError(
|
1431 |
+
f"argument of 'makeelement' parameter must be callable, got {type(makeelement)}")
|
1432 |
+
self._makeelement = makeelement
|
1433 |
+
else:
|
1434 |
+
self._makeelement = None
|
1435 |
+
self._cache = {}
|
1436 |
+
|
1437 |
+
@cython.final
|
1438 |
+
cdef _build_element_maker(self, tag, bint caching):
|
1439 |
+
cdef _ObjectifyElementMakerCaller element_maker
|
1440 |
+
element_maker = _ObjectifyElementMakerCaller.__new__(_ObjectifyElementMakerCaller)
|
1441 |
+
if self._namespace is not None and tag[0] != "{":
|
1442 |
+
element_maker._tag = self._namespace + tag
|
1443 |
+
else:
|
1444 |
+
element_maker._tag = tag
|
1445 |
+
element_maker._nsmap = self._nsmap
|
1446 |
+
element_maker._annotate = self._annotate
|
1447 |
+
element_maker._element_factory = self._makeelement
|
1448 |
+
if caching:
|
1449 |
+
if len(self._cache) > 200:
|
1450 |
+
self._cache.clear()
|
1451 |
+
self._cache[tag] = element_maker
|
1452 |
+
return element_maker
|
1453 |
+
|
1454 |
+
def __getattr__(self, tag):
|
1455 |
+
element_maker = self._cache.get(tag)
|
1456 |
+
if element_maker is None:
|
1457 |
+
return self._build_element_maker(tag, caching=True)
|
1458 |
+
return element_maker
|
1459 |
+
|
1460 |
+
def __call__(self, tag, *args, **kwargs):
|
1461 |
+
element_maker = self._cache.get(tag)
|
1462 |
+
if element_maker is None:
|
1463 |
+
element_maker = self._build_element_maker(
|
1464 |
+
tag, caching=not is_special_method(tag))
|
1465 |
+
return element_maker(*args, **kwargs)
|
1466 |
+
|
1467 |
+
################################################################################
|
1468 |
+
# Recursive element dumping
|
1469 |
+
|
1470 |
+
cdef bint __RECURSIVE_STR = 0 # default: off
|
1471 |
+
|
1472 |
+
def enable_recursive_str(on=True):
|
1473 |
+
"""enable_recursive_str(on=True)
|
1474 |
+
|
1475 |
+
Enable a recursively generated tree representation for str(element),
|
1476 |
+
based on objectify.dump(element).
|
1477 |
+
"""
|
1478 |
+
global __RECURSIVE_STR
|
1479 |
+
__RECURSIVE_STR = on
|
1480 |
+
|
1481 |
+
def dump(_Element element not None):
|
1482 |
+
"""dump(_Element element not None)
|
1483 |
+
|
1484 |
+
Return a recursively generated string representation of an element.
|
1485 |
+
"""
|
1486 |
+
return _dump(element, 0)
|
1487 |
+
|
1488 |
+
cdef object _dump(_Element element, int indent):
|
1489 |
+
indentstr = " " * indent
|
1490 |
+
if isinstance(element, ObjectifiedDataElement):
|
1491 |
+
value = repr(element)
|
1492 |
+
else:
|
1493 |
+
value = textOf(element._c_node)
|
1494 |
+
if value is not None:
|
1495 |
+
if not value.strip():
|
1496 |
+
value = None
|
1497 |
+
else:
|
1498 |
+
value = repr(value)
|
1499 |
+
result = f"{indentstr}{element.tag} = {value} [{_typename(element)}]\n"
|
1500 |
+
xsi_ns = "{%s}" % XML_SCHEMA_INSTANCE_NS
|
1501 |
+
pytype_ns = "{%s}" % PYTYPE_NAMESPACE
|
1502 |
+
for name, value in sorted(cetree.iterattributes(element, 3)):
|
1503 |
+
if '{' in name:
|
1504 |
+
if name == PYTYPE_ATTRIBUTE:
|
1505 |
+
if value == TREE_PYTYPE_NAME:
|
1506 |
+
continue
|
1507 |
+
else:
|
1508 |
+
name = name.replace(pytype_ns, 'py:')
|
1509 |
+
name = name.replace(xsi_ns, 'xsi:')
|
1510 |
+
result += f"{indentstr} * {name} = {value!r}\n"
|
1511 |
+
|
1512 |
+
indent += 1
|
1513 |
+
for child in element.iterchildren():
|
1514 |
+
result += _dump(child, indent)
|
1515 |
+
if indent == 1:
|
1516 |
+
return result[:-1] # strip last '\n'
|
1517 |
+
else:
|
1518 |
+
return result
|
1519 |
+
|
1520 |
+
|
1521 |
+
################################################################################
|
1522 |
+
# Pickle support for objectified ElementTree
|
1523 |
+
|
1524 |
+
def __unpickleElementTree(data):
|
1525 |
+
return etree.ElementTree(fromstring(data))
|
1526 |
+
|
1527 |
+
cdef _setupPickle(elementTreeReduceFunction):
|
1528 |
+
import copyreg
|
1529 |
+
copyreg.pickle(etree._ElementTree,
|
1530 |
+
elementTreeReduceFunction, __unpickleElementTree)
|
1531 |
+
|
1532 |
+
def pickleReduceElementTree(obj):
|
1533 |
+
return __unpickleElementTree, (etree.tostring(obj),)
|
1534 |
+
|
1535 |
+
_setupPickle(pickleReduceElementTree)
|
1536 |
+
del pickleReduceElementTree
|
1537 |
+
|
1538 |
+
################################################################################
|
1539 |
+
# Element class lookup
|
1540 |
+
|
1541 |
+
cdef class ObjectifyElementClassLookup(ElementClassLookup):
|
1542 |
+
"""ObjectifyElementClassLookup(self, tree_class=None, empty_data_class=None)
|
1543 |
+
Element class lookup method that uses the objectify classes.
|
1544 |
+
"""
|
1545 |
+
cdef object empty_data_class
|
1546 |
+
cdef object tree_class
|
1547 |
+
def __init__(self, tree_class=None, empty_data_class=None):
|
1548 |
+
"""Lookup mechanism for objectify.
|
1549 |
+
|
1550 |
+
The default Element classes can be replaced by passing subclasses of
|
1551 |
+
ObjectifiedElement and ObjectifiedDataElement as keyword arguments.
|
1552 |
+
'tree_class' defines inner tree classes (defaults to
|
1553 |
+
ObjectifiedElement), 'empty_data_class' defines the default class for
|
1554 |
+
empty data elements (defaults to StringElement).
|
1555 |
+
"""
|
1556 |
+
self._lookup_function = _lookupElementClass
|
1557 |
+
if tree_class is None:
|
1558 |
+
tree_class = ObjectifiedElement
|
1559 |
+
self.tree_class = tree_class
|
1560 |
+
if empty_data_class is None:
|
1561 |
+
empty_data_class = StringElement
|
1562 |
+
self.empty_data_class = empty_data_class
|
1563 |
+
|
1564 |
+
cdef object _lookupElementClass(state, _Document doc, tree.xmlNode* c_node):
|
1565 |
+
cdef ObjectifyElementClassLookup lookup
|
1566 |
+
lookup = <ObjectifyElementClassLookup>state
|
1567 |
+
# if element has children => no data class
|
1568 |
+
if cetree.hasChild(c_node):
|
1569 |
+
return lookup.tree_class
|
1570 |
+
|
1571 |
+
# if element is defined as xsi:nil, return NoneElement class
|
1572 |
+
if "true" == cetree.attributeValueFromNsName(
|
1573 |
+
c_node, _XML_SCHEMA_INSTANCE_NS, <unsigned char*>"nil"):
|
1574 |
+
return NoneElement
|
1575 |
+
|
1576 |
+
# check for Python type hint
|
1577 |
+
value = cetree.attributeValueFromNsName(
|
1578 |
+
c_node, _PYTYPE_NAMESPACE, _PYTYPE_ATTRIBUTE_NAME)
|
1579 |
+
if value is not None:
|
1580 |
+
if value == TREE_PYTYPE_NAME:
|
1581 |
+
return lookup.tree_class
|
1582 |
+
py_type = <PyType>_PYTYPE_DICT.get(value)
|
1583 |
+
if py_type is not None:
|
1584 |
+
return py_type._type
|
1585 |
+
# unknown 'pyval' => try to figure it out ourself, just go on
|
1586 |
+
|
1587 |
+
# check for XML Schema type hint
|
1588 |
+
value = cetree.attributeValueFromNsName(
|
1589 |
+
c_node, _XML_SCHEMA_INSTANCE_NS, <unsigned char*>"type")
|
1590 |
+
|
1591 |
+
if value is not None:
|
1592 |
+
schema_type = <PyType>_SCHEMA_TYPE_DICT.get(value)
|
1593 |
+
if schema_type is None and ':' in value:
|
1594 |
+
prefix, value = value.split(':', 1)
|
1595 |
+
schema_type = <PyType>_SCHEMA_TYPE_DICT.get(value)
|
1596 |
+
if schema_type is not None:
|
1597 |
+
return schema_type._type
|
1598 |
+
|
1599 |
+
# otherwise determine class based on text content type
|
1600 |
+
el_class = _guessElementClass(c_node)
|
1601 |
+
if el_class is not None:
|
1602 |
+
return el_class
|
1603 |
+
|
1604 |
+
# if element is a root node => default to tree node
|
1605 |
+
if c_node.parent is NULL or not tree._isElement(c_node.parent):
|
1606 |
+
return lookup.tree_class
|
1607 |
+
|
1608 |
+
return lookup.empty_data_class
|
1609 |
+
|
1610 |
+
|
1611 |
+
################################################################################
|
1612 |
+
# Type annotations
|
1613 |
+
|
1614 |
+
cdef PyType _check_type(tree.xmlNode* c_node, PyType pytype):
|
1615 |
+
if pytype is None:
|
1616 |
+
return None
|
1617 |
+
value = textOf(c_node)
|
1618 |
+
try:
|
1619 |
+
pytype.type_check(value)
|
1620 |
+
return pytype
|
1621 |
+
except IGNORABLE_ERRORS:
|
1622 |
+
# could not be parsed as the specified type => ignore
|
1623 |
+
pass
|
1624 |
+
return None
|
1625 |
+
|
1626 |
+
def pyannotate(element_or_tree, *, ignore_old=False, ignore_xsi=False,
|
1627 |
+
empty_pytype=None):
|
1628 |
+
"""pyannotate(element_or_tree, ignore_old=False, ignore_xsi=False, empty_pytype=None)
|
1629 |
+
|
1630 |
+
Recursively annotates the elements of an XML tree with 'pytype'
|
1631 |
+
attributes.
|
1632 |
+
|
1633 |
+
If the 'ignore_old' keyword argument is True (the default), current 'pytype'
|
1634 |
+
attributes will be ignored and replaced. Otherwise, they will be checked
|
1635 |
+
and only replaced if they no longer fit the current text value.
|
1636 |
+
|
1637 |
+
Setting the keyword argument ``ignore_xsi`` to True makes the function
|
1638 |
+
additionally ignore existing ``xsi:type`` annotations. The default is to
|
1639 |
+
use them as a type hint.
|
1640 |
+
|
1641 |
+
The default annotation of empty elements can be set with the
|
1642 |
+
``empty_pytype`` keyword argument. The default is not to annotate empty
|
1643 |
+
elements. Pass 'str', for example, to make string values the default.
|
1644 |
+
"""
|
1645 |
+
cdef _Element element
|
1646 |
+
element = cetree.rootNodeOrRaise(element_or_tree)
|
1647 |
+
_annotate(element, 0, 1, ignore_xsi, ignore_old, None, empty_pytype)
|
1648 |
+
|
1649 |
+
def xsiannotate(element_or_tree, *, ignore_old=False, ignore_pytype=False,
|
1650 |
+
empty_type=None):
|
1651 |
+
"""xsiannotate(element_or_tree, ignore_old=False, ignore_pytype=False, empty_type=None)
|
1652 |
+
|
1653 |
+
Recursively annotates the elements of an XML tree with 'xsi:type'
|
1654 |
+
attributes.
|
1655 |
+
|
1656 |
+
If the 'ignore_old' keyword argument is True (the default), current
|
1657 |
+
'xsi:type' attributes will be ignored and replaced. Otherwise, they will be
|
1658 |
+
checked and only replaced if they no longer fit the current text value.
|
1659 |
+
|
1660 |
+
Note that the mapping from Python types to XSI types is usually ambiguous.
|
1661 |
+
Currently, only the first XSI type name in the corresponding PyType
|
1662 |
+
definition will be used for annotation. Thus, you should consider naming
|
1663 |
+
the widest type first if you define additional types.
|
1664 |
+
|
1665 |
+
Setting the keyword argument ``ignore_pytype`` to True makes the function
|
1666 |
+
additionally ignore existing ``pytype`` annotations. The default is to
|
1667 |
+
use them as a type hint.
|
1668 |
+
|
1669 |
+
The default annotation of empty elements can be set with the
|
1670 |
+
``empty_type`` keyword argument. The default is not to annotate empty
|
1671 |
+
elements. Pass 'string', for example, to make string values the default.
|
1672 |
+
"""
|
1673 |
+
cdef _Element element
|
1674 |
+
element = cetree.rootNodeOrRaise(element_or_tree)
|
1675 |
+
_annotate(element, 1, 0, ignore_old, ignore_pytype, empty_type, None)
|
1676 |
+
|
1677 |
+
def annotate(element_or_tree, *, ignore_old=True, ignore_xsi=False,
|
1678 |
+
empty_pytype=None, empty_type=None, annotate_xsi=0,
|
1679 |
+
annotate_pytype=1):
|
1680 |
+
"""annotate(element_or_tree, ignore_old=True, ignore_xsi=False, empty_pytype=None, empty_type=None, annotate_xsi=0, annotate_pytype=1)
|
1681 |
+
|
1682 |
+
Recursively annotates the elements of an XML tree with 'xsi:type'
|
1683 |
+
and/or 'py:pytype' attributes.
|
1684 |
+
|
1685 |
+
If the 'ignore_old' keyword argument is True (the default), current
|
1686 |
+
'py:pytype' attributes will be ignored for the type annotation. Set to False
|
1687 |
+
if you want reuse existing 'py:pytype' information (iff appropriate for the
|
1688 |
+
element text value).
|
1689 |
+
|
1690 |
+
If the 'ignore_xsi' keyword argument is False (the default), existing
|
1691 |
+
'xsi:type' attributes will be used for the type annotation, if they fit the
|
1692 |
+
element text values.
|
1693 |
+
|
1694 |
+
Note that the mapping from Python types to XSI types is usually ambiguous.
|
1695 |
+
Currently, only the first XSI type name in the corresponding PyType
|
1696 |
+
definition will be used for annotation. Thus, you should consider naming
|
1697 |
+
the widest type first if you define additional types.
|
1698 |
+
|
1699 |
+
The default 'py:pytype' annotation of empty elements can be set with the
|
1700 |
+
``empty_pytype`` keyword argument. Pass 'str', for example, to make
|
1701 |
+
string values the default.
|
1702 |
+
|
1703 |
+
The default 'xsi:type' annotation of empty elements can be set with the
|
1704 |
+
``empty_type`` keyword argument. The default is not to annotate empty
|
1705 |
+
elements. Pass 'string', for example, to make string values the default.
|
1706 |
+
|
1707 |
+
The keyword arguments 'annotate_xsi' (default: 0) and 'annotate_pytype'
|
1708 |
+
(default: 1) control which kind(s) of annotation to use.
|
1709 |
+
"""
|
1710 |
+
cdef _Element element
|
1711 |
+
element = cetree.rootNodeOrRaise(element_or_tree)
|
1712 |
+
_annotate(element, annotate_xsi, annotate_pytype, ignore_xsi,
|
1713 |
+
ignore_old, empty_type, empty_pytype)
|
1714 |
+
|
1715 |
+
|
1716 |
+
cdef _annotate(_Element element, bint annotate_xsi, bint annotate_pytype,
|
1717 |
+
bint ignore_xsi, bint ignore_pytype,
|
1718 |
+
empty_type_name, empty_pytype_name):
|
1719 |
+
cdef _Document doc
|
1720 |
+
cdef tree.xmlNode* c_node
|
1721 |
+
cdef PyType empty_pytype, StrType, NoneType
|
1722 |
+
|
1723 |
+
if not annotate_xsi and not annotate_pytype:
|
1724 |
+
return
|
1725 |
+
|
1726 |
+
if empty_type_name is not None:
|
1727 |
+
if isinstance(empty_type_name, bytes):
|
1728 |
+
empty_type_name = (<bytes>empty_type_name).decode("ascii")
|
1729 |
+
empty_pytype = <PyType>_SCHEMA_TYPE_DICT.get(empty_type_name)
|
1730 |
+
elif empty_pytype_name is not None:
|
1731 |
+
if isinstance(empty_pytype_name, bytes):
|
1732 |
+
empty_pytype_name = (<bytes>empty_pytype_name).decode("ascii")
|
1733 |
+
empty_pytype = <PyType>_PYTYPE_DICT.get(empty_pytype_name)
|
1734 |
+
else:
|
1735 |
+
empty_pytype = None
|
1736 |
+
|
1737 |
+
StrType = <PyType>_PYTYPE_DICT.get('str')
|
1738 |
+
NoneType = <PyType>_PYTYPE_DICT.get('NoneType')
|
1739 |
+
|
1740 |
+
doc = element._doc
|
1741 |
+
c_node = element._c_node
|
1742 |
+
tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_node, c_node, 1)
|
1743 |
+
if c_node.type == tree.XML_ELEMENT_NODE:
|
1744 |
+
_annotate_element(c_node, doc, annotate_xsi, annotate_pytype,
|
1745 |
+
ignore_xsi, ignore_pytype,
|
1746 |
+
empty_type_name, empty_pytype, StrType, NoneType)
|
1747 |
+
tree.END_FOR_EACH_ELEMENT_FROM(c_node)
|
1748 |
+
|
1749 |
+
cdef int _annotate_element(tree.xmlNode* c_node, _Document doc,
|
1750 |
+
bint annotate_xsi, bint annotate_pytype,
|
1751 |
+
bint ignore_xsi, bint ignore_pytype,
|
1752 |
+
empty_type_name, PyType empty_pytype,
|
1753 |
+
PyType StrType, PyType NoneType) except -1:
|
1754 |
+
cdef tree.xmlNs* c_ns
|
1755 |
+
cdef PyType pytype = None
|
1756 |
+
typename = None
|
1757 |
+
istree = 0
|
1758 |
+
|
1759 |
+
# if element is defined as xsi:nil, represent it as None
|
1760 |
+
if cetree.attributeValueFromNsName(
|
1761 |
+
c_node, _XML_SCHEMA_INSTANCE_NS, <unsigned char*>"nil") == "true":
|
1762 |
+
pytype = NoneType
|
1763 |
+
|
1764 |
+
if pytype is None and not ignore_xsi:
|
1765 |
+
# check that old xsi type value is valid
|
1766 |
+
typename = cetree.attributeValueFromNsName(
|
1767 |
+
c_node, _XML_SCHEMA_INSTANCE_NS, <unsigned char*>"type")
|
1768 |
+
if typename is not None:
|
1769 |
+
pytype = <PyType>_SCHEMA_TYPE_DICT.get(typename)
|
1770 |
+
if pytype is None and ':' in typename:
|
1771 |
+
prefix, typename = typename.split(':', 1)
|
1772 |
+
pytype = <PyType>_SCHEMA_TYPE_DICT.get(typename)
|
1773 |
+
if pytype is not None and pytype is not StrType:
|
1774 |
+
# StrType does not have a typecheck but is the default
|
1775 |
+
# anyway, so just accept it if given as type
|
1776 |
+
# information
|
1777 |
+
pytype = _check_type(c_node, pytype)
|
1778 |
+
if pytype is None:
|
1779 |
+
typename = None
|
1780 |
+
|
1781 |
+
if pytype is None and not ignore_pytype:
|
1782 |
+
# check that old pytype value is valid
|
1783 |
+
old_pytypename = cetree.attributeValueFromNsName(
|
1784 |
+
c_node, _PYTYPE_NAMESPACE, _PYTYPE_ATTRIBUTE_NAME)
|
1785 |
+
if old_pytypename is not None:
|
1786 |
+
if old_pytypename == TREE_PYTYPE_NAME:
|
1787 |
+
if not cetree.hasChild(c_node):
|
1788 |
+
# only case where we should keep it,
|
1789 |
+
# everything else is clear enough
|
1790 |
+
pytype = TREE_PYTYPE
|
1791 |
+
else:
|
1792 |
+
if old_pytypename == 'none':
|
1793 |
+
# transition from lxml 1.x
|
1794 |
+
old_pytypename = "NoneType"
|
1795 |
+
pytype = <PyType>_PYTYPE_DICT.get(old_pytypename)
|
1796 |
+
if pytype is not None and pytype is not StrType:
|
1797 |
+
# StrType does not have a typecheck but is the
|
1798 |
+
# default anyway, so just accept it if given as
|
1799 |
+
# type information
|
1800 |
+
pytype = _check_type(c_node, pytype)
|
1801 |
+
|
1802 |
+
if pytype is None:
|
1803 |
+
# try to guess type
|
1804 |
+
if not cetree.hasChild(c_node):
|
1805 |
+
# element has no children => data class
|
1806 |
+
pytype = _guessPyType(textOf(c_node), StrType)
|
1807 |
+
else:
|
1808 |
+
istree = 1
|
1809 |
+
|
1810 |
+
if pytype is None:
|
1811 |
+
# use default type for empty elements
|
1812 |
+
if cetree.hasText(c_node):
|
1813 |
+
pytype = StrType
|
1814 |
+
else:
|
1815 |
+
pytype = empty_pytype
|
1816 |
+
if typename is None:
|
1817 |
+
typename = empty_type_name
|
1818 |
+
|
1819 |
+
if pytype is not None:
|
1820 |
+
if typename is None:
|
1821 |
+
if not istree:
|
1822 |
+
if pytype._schema_types:
|
1823 |
+
# pytype->xsi:type is a 1:n mapping
|
1824 |
+
# simply take the first
|
1825 |
+
typename = pytype._schema_types[0]
|
1826 |
+
elif typename not in pytype._schema_types:
|
1827 |
+
typename = pytype._schema_types[0]
|
1828 |
+
|
1829 |
+
if annotate_xsi:
|
1830 |
+
if typename is None or istree:
|
1831 |
+
cetree.delAttributeFromNsName(
|
1832 |
+
c_node, _XML_SCHEMA_INSTANCE_NS, <unsigned char*>"type")
|
1833 |
+
else:
|
1834 |
+
# update or create attribute
|
1835 |
+
typename_utf8 = cetree.utf8(typename)
|
1836 |
+
c_ns = cetree.findOrBuildNodeNsPrefix(
|
1837 |
+
doc, c_node, _XML_SCHEMA_NS, <unsigned char*>'xsd')
|
1838 |
+
if c_ns is not NULL:
|
1839 |
+
if b':' in typename_utf8:
|
1840 |
+
prefix, name = typename_utf8.split(b':', 1)
|
1841 |
+
if c_ns.prefix is NULL or c_ns.prefix[0] == c'\0':
|
1842 |
+
typename_utf8 = name
|
1843 |
+
elif tree.xmlStrcmp(_xcstr(prefix), c_ns.prefix) != 0:
|
1844 |
+
typename_utf8 = (<unsigned char*>c_ns.prefix) + b':' + name
|
1845 |
+
elif c_ns.prefix is not NULL and c_ns.prefix[0] != c'\0':
|
1846 |
+
typename_utf8 = (<unsigned char*>c_ns.prefix) + b':' + typename_utf8
|
1847 |
+
c_ns = cetree.findOrBuildNodeNsPrefix(
|
1848 |
+
doc, c_node, _XML_SCHEMA_INSTANCE_NS, <unsigned char*>'xsi')
|
1849 |
+
tree.xmlSetNsProp(c_node, c_ns, <unsigned char*>"type", _xcstr(typename_utf8))
|
1850 |
+
|
1851 |
+
if annotate_pytype:
|
1852 |
+
if pytype is None:
|
1853 |
+
# delete attribute if it exists
|
1854 |
+
cetree.delAttributeFromNsName(
|
1855 |
+
c_node, _PYTYPE_NAMESPACE, _PYTYPE_ATTRIBUTE_NAME)
|
1856 |
+
else:
|
1857 |
+
# update or create attribute
|
1858 |
+
c_ns = cetree.findOrBuildNodeNsPrefix(
|
1859 |
+
doc, c_node, _PYTYPE_NAMESPACE, <unsigned char*>'py')
|
1860 |
+
pytype_name = cetree.utf8(pytype.name)
|
1861 |
+
tree.xmlSetNsProp(c_node, c_ns, _PYTYPE_ATTRIBUTE_NAME,
|
1862 |
+
_xcstr(pytype_name))
|
1863 |
+
if pytype is NoneType:
|
1864 |
+
c_ns = cetree.findOrBuildNodeNsPrefix(
|
1865 |
+
doc, c_node, _XML_SCHEMA_INSTANCE_NS, <unsigned char*>'xsi')
|
1866 |
+
tree.xmlSetNsProp(c_node, c_ns, <unsigned char*>"nil", <unsigned char*>"true")
|
1867 |
+
|
1868 |
+
return 0
|
1869 |
+
|
1870 |
+
cdef object _strip_attributes = etree.strip_attributes
|
1871 |
+
cdef object _cleanup_namespaces = etree.cleanup_namespaces
|
1872 |
+
|
1873 |
+
def deannotate(element_or_tree, *, bint pytype=True, bint xsi=True,
|
1874 |
+
bint xsi_nil=False, bint cleanup_namespaces=False):
|
1875 |
+
"""deannotate(element_or_tree, pytype=True, xsi=True, xsi_nil=False, cleanup_namespaces=False)
|
1876 |
+
|
1877 |
+
Recursively de-annotate the elements of an XML tree by removing 'py:pytype'
|
1878 |
+
and/or 'xsi:type' attributes and/or 'xsi:nil' attributes.
|
1879 |
+
|
1880 |
+
If the 'pytype' keyword argument is True (the default), 'py:pytype'
|
1881 |
+
attributes will be removed. If the 'xsi' keyword argument is True (the
|
1882 |
+
default), 'xsi:type' attributes will be removed.
|
1883 |
+
If the 'xsi_nil' keyword argument is True (default: False), 'xsi:nil'
|
1884 |
+
attributes will be removed.
|
1885 |
+
|
1886 |
+
Note that this does not touch the namespace declarations by
|
1887 |
+
default. If you want to remove unused namespace declarations from
|
1888 |
+
the tree, pass the option ``cleanup_namespaces=True``.
|
1889 |
+
"""
|
1890 |
+
cdef list attribute_names = []
|
1891 |
+
|
1892 |
+
if pytype:
|
1893 |
+
attribute_names.append(PYTYPE_ATTRIBUTE)
|
1894 |
+
if xsi:
|
1895 |
+
attribute_names.append(XML_SCHEMA_INSTANCE_TYPE_ATTR)
|
1896 |
+
if xsi_nil:
|
1897 |
+
attribute_names.append(XML_SCHEMA_INSTANCE_NIL_ATTR)
|
1898 |
+
|
1899 |
+
_strip_attributes(element_or_tree, *attribute_names)
|
1900 |
+
if cleanup_namespaces:
|
1901 |
+
_cleanup_namespaces(element_or_tree)
|
1902 |
+
|
1903 |
+
################################################################################
|
1904 |
+
# Module level parser setup
|
1905 |
+
|
1906 |
+
cdef object __DEFAULT_PARSER
|
1907 |
+
__DEFAULT_PARSER = etree.XMLParser(remove_blank_text=True)
|
1908 |
+
__DEFAULT_PARSER.set_element_class_lookup( ObjectifyElementClassLookup() )
|
1909 |
+
|
1910 |
+
cdef object objectify_parser
|
1911 |
+
objectify_parser = __DEFAULT_PARSER
|
1912 |
+
|
1913 |
+
def set_default_parser(new_parser = None):
|
1914 |
+
"""set_default_parser(new_parser = None)
|
1915 |
+
|
1916 |
+
Replace the default parser used by objectify's Element() and
|
1917 |
+
fromstring() functions.
|
1918 |
+
|
1919 |
+
The new parser must be an etree.XMLParser.
|
1920 |
+
|
1921 |
+
Call without arguments to reset to the original parser.
|
1922 |
+
"""
|
1923 |
+
global objectify_parser
|
1924 |
+
if new_parser is None:
|
1925 |
+
objectify_parser = __DEFAULT_PARSER
|
1926 |
+
elif isinstance(new_parser, etree.XMLParser):
|
1927 |
+
objectify_parser = new_parser
|
1928 |
+
else:
|
1929 |
+
raise TypeError, "parser must inherit from lxml.etree.XMLParser"
|
1930 |
+
|
1931 |
+
def makeparser(**kw):
|
1932 |
+
"""makeparser(remove_blank_text=True, **kw)
|
1933 |
+
|
1934 |
+
Create a new XML parser for objectify trees.
|
1935 |
+
|
1936 |
+
You can pass all keyword arguments that are supported by
|
1937 |
+
``etree.XMLParser()``. Note that this parser defaults to removing
|
1938 |
+
blank text. You can disable this by passing the
|
1939 |
+
``remove_blank_text`` boolean keyword option yourself.
|
1940 |
+
"""
|
1941 |
+
if 'remove_blank_text' not in kw:
|
1942 |
+
kw['remove_blank_text'] = True
|
1943 |
+
parser = etree.XMLParser(**kw)
|
1944 |
+
parser.set_element_class_lookup( ObjectifyElementClassLookup() )
|
1945 |
+
return parser
|
1946 |
+
|
1947 |
+
cdef _Element _makeElement(tag, text, attrib, nsmap):
|
1948 |
+
return cetree.makeElement(tag, None, objectify_parser, text, None, attrib, nsmap)
|
1949 |
+
|
1950 |
+
################################################################################
|
1951 |
+
# Module level factory functions
|
1952 |
+
|
1953 |
+
cdef object _fromstring
|
1954 |
+
_fromstring = etree.fromstring
|
1955 |
+
|
1956 |
+
SubElement = etree.SubElement
|
1957 |
+
|
1958 |
+
def fromstring(xml, parser=None, *, base_url=None):
|
1959 |
+
"""fromstring(xml, parser=None, base_url=None)
|
1960 |
+
|
1961 |
+
Objectify specific version of the lxml.etree fromstring() function
|
1962 |
+
that uses the objectify parser.
|
1963 |
+
|
1964 |
+
You can pass a different parser as second argument.
|
1965 |
+
|
1966 |
+
The ``base_url`` keyword argument allows to set the original base URL of
|
1967 |
+
the document to support relative Paths when looking up external entities
|
1968 |
+
(DTD, XInclude, ...).
|
1969 |
+
"""
|
1970 |
+
if parser is None:
|
1971 |
+
parser = objectify_parser
|
1972 |
+
return _fromstring(xml, parser, base_url=base_url)
|
1973 |
+
|
1974 |
+
def XML(xml, parser=None, *, base_url=None):
|
1975 |
+
"""XML(xml, parser=None, base_url=None)
|
1976 |
+
|
1977 |
+
Objectify specific version of the lxml.etree XML() literal factory
|
1978 |
+
that uses the objectify parser.
|
1979 |
+
|
1980 |
+
You can pass a different parser as second argument.
|
1981 |
+
|
1982 |
+
The ``base_url`` keyword argument allows to set the original base URL of
|
1983 |
+
the document to support relative Paths when looking up external entities
|
1984 |
+
(DTD, XInclude, ...).
|
1985 |
+
"""
|
1986 |
+
if parser is None:
|
1987 |
+
parser = objectify_parser
|
1988 |
+
return _fromstring(xml, parser, base_url=base_url)
|
1989 |
+
|
1990 |
+
cdef object _parse
|
1991 |
+
_parse = etree.parse
|
1992 |
+
|
1993 |
+
def parse(f, parser=None, *, base_url=None):
|
1994 |
+
"""parse(f, parser=None, base_url=None)
|
1995 |
+
|
1996 |
+
Parse a file or file-like object with the objectify parser.
|
1997 |
+
|
1998 |
+
You can pass a different parser as second argument.
|
1999 |
+
|
2000 |
+
The ``base_url`` keyword allows setting a URL for the document
|
2001 |
+
when parsing from a file-like object. This is needed when looking
|
2002 |
+
up external entities (DTD, XInclude, ...) with relative paths.
|
2003 |
+
"""
|
2004 |
+
if parser is None:
|
2005 |
+
parser = objectify_parser
|
2006 |
+
return _parse(f, parser, base_url=base_url)
|
2007 |
+
|
2008 |
+
cdef dict _DEFAULT_NSMAP = {
|
2009 |
+
"py" : PYTYPE_NAMESPACE,
|
2010 |
+
"xsi" : XML_SCHEMA_INSTANCE_NS,
|
2011 |
+
"xsd" : XML_SCHEMA_NS
|
2012 |
+
}
|
2013 |
+
|
2014 |
+
E = ElementMaker()
|
2015 |
+
|
2016 |
+
def Element(_tag, attrib=None, nsmap=None, *, _pytype=None, **_attributes):
|
2017 |
+
"""Element(_tag, attrib=None, nsmap=None, _pytype=None, **_attributes)
|
2018 |
+
|
2019 |
+
Objectify specific version of the lxml.etree Element() factory that
|
2020 |
+
always creates a structural (tree) element.
|
2021 |
+
|
2022 |
+
NOTE: requires parser based element class lookup activated in lxml.etree!
|
2023 |
+
"""
|
2024 |
+
if attrib is not None:
|
2025 |
+
if _attributes:
|
2026 |
+
attrib = dict(attrib)
|
2027 |
+
attrib.update(_attributes)
|
2028 |
+
_attributes = attrib
|
2029 |
+
if _pytype is None:
|
2030 |
+
_pytype = TREE_PYTYPE_NAME
|
2031 |
+
if nsmap is None:
|
2032 |
+
nsmap = _DEFAULT_NSMAP
|
2033 |
+
_attributes[PYTYPE_ATTRIBUTE] = _pytype
|
2034 |
+
return _makeElement(_tag, None, _attributes, nsmap)
|
2035 |
+
|
2036 |
+
def DataElement(_value, attrib=None, nsmap=None, *, _pytype=None, _xsi=None,
|
2037 |
+
**_attributes):
|
2038 |
+
"""DataElement(_value, attrib=None, nsmap=None, _pytype=None, _xsi=None, **_attributes)
|
2039 |
+
|
2040 |
+
Create a new element from a Python value and XML attributes taken from
|
2041 |
+
keyword arguments or a dictionary passed as second argument.
|
2042 |
+
|
2043 |
+
Automatically adds a 'pytype' attribute for the Python type of the value,
|
2044 |
+
if the type can be identified. If '_pytype' or '_xsi' are among the
|
2045 |
+
keyword arguments, they will be used instead.
|
2046 |
+
|
2047 |
+
If the _value argument is an ObjectifiedDataElement instance, its py:pytype,
|
2048 |
+
xsi:type and other attributes and nsmap are reused unless they are redefined
|
2049 |
+
in attrib and/or keyword arguments.
|
2050 |
+
"""
|
2051 |
+
if nsmap is None:
|
2052 |
+
nsmap = _DEFAULT_NSMAP
|
2053 |
+
if attrib is not None and attrib:
|
2054 |
+
if _attributes:
|
2055 |
+
attrib = dict(attrib)
|
2056 |
+
attrib.update(_attributes)
|
2057 |
+
_attributes = attrib
|
2058 |
+
if isinstance(_value, ObjectifiedElement):
|
2059 |
+
if _pytype is None:
|
2060 |
+
if _xsi is None and not _attributes and nsmap is _DEFAULT_NSMAP:
|
2061 |
+
# special case: no change!
|
2062 |
+
return _value.__copy__()
|
2063 |
+
if isinstance(_value, ObjectifiedDataElement):
|
2064 |
+
# reuse existing nsmap unless redefined in nsmap parameter
|
2065 |
+
temp = _value.nsmap
|
2066 |
+
if temp is not None and temp:
|
2067 |
+
temp = dict(temp)
|
2068 |
+
temp.update(nsmap)
|
2069 |
+
nsmap = temp
|
2070 |
+
# reuse existing attributes unless redefined in attrib/_attributes
|
2071 |
+
temp = _value.attrib
|
2072 |
+
if temp is not None and temp:
|
2073 |
+
temp = dict(temp)
|
2074 |
+
temp.update(_attributes)
|
2075 |
+
_attributes = temp
|
2076 |
+
# reuse existing xsi:type or py:pytype attributes, unless provided as
|
2077 |
+
# arguments
|
2078 |
+
if _xsi is None and _pytype is None:
|
2079 |
+
_xsi = _attributes.get(XML_SCHEMA_INSTANCE_TYPE_ATTR)
|
2080 |
+
_pytype = _attributes.get(PYTYPE_ATTRIBUTE)
|
2081 |
+
|
2082 |
+
if _xsi is not None:
|
2083 |
+
if ':' in _xsi:
|
2084 |
+
prefix, name = _xsi.split(':', 1)
|
2085 |
+
ns = nsmap.get(prefix)
|
2086 |
+
if ns != XML_SCHEMA_NS:
|
2087 |
+
raise ValueError, "XSD types require the XSD namespace"
|
2088 |
+
elif nsmap is _DEFAULT_NSMAP:
|
2089 |
+
name = _xsi
|
2090 |
+
_xsi = 'xsd:' + _xsi
|
2091 |
+
else:
|
2092 |
+
name = _xsi
|
2093 |
+
for prefix, ns in nsmap.items():
|
2094 |
+
if ns == XML_SCHEMA_NS:
|
2095 |
+
if prefix is not None and prefix:
|
2096 |
+
_xsi = prefix + ':' + _xsi
|
2097 |
+
break
|
2098 |
+
else:
|
2099 |
+
raise ValueError, "XSD types require the XSD namespace"
|
2100 |
+
_attributes[XML_SCHEMA_INSTANCE_TYPE_ATTR] = _xsi
|
2101 |
+
if _pytype is None:
|
2102 |
+
# allow using unregistered or even wrong xsi:type names
|
2103 |
+
py_type = <PyType>_SCHEMA_TYPE_DICT.get(_xsi)
|
2104 |
+
if py_type is None:
|
2105 |
+
py_type = <PyType>_SCHEMA_TYPE_DICT.get(name)
|
2106 |
+
if py_type is not None:
|
2107 |
+
_pytype = py_type.name
|
2108 |
+
|
2109 |
+
if _pytype is None:
|
2110 |
+
_pytype = _pytypename(_value)
|
2111 |
+
|
2112 |
+
if _value is None and _pytype != "str":
|
2113 |
+
_pytype = _pytype or "NoneType"
|
2114 |
+
strval = None
|
2115 |
+
elif python._isString(_value):
|
2116 |
+
strval = _value
|
2117 |
+
elif isinstance(_value, bool):
|
2118 |
+
if _value:
|
2119 |
+
strval = "true"
|
2120 |
+
else:
|
2121 |
+
strval = "false"
|
2122 |
+
else:
|
2123 |
+
py_type = <PyType>_PYTYPE_DICT.get(_pytype)
|
2124 |
+
stringify = unicode if py_type is None else py_type.stringify
|
2125 |
+
strval = stringify(_value)
|
2126 |
+
|
2127 |
+
if _pytype is not None:
|
2128 |
+
if _pytype == "NoneType" or _pytype == "none":
|
2129 |
+
strval = None
|
2130 |
+
_attributes[XML_SCHEMA_INSTANCE_NIL_ATTR] = "true"
|
2131 |
+
else:
|
2132 |
+
# check if type information from arguments is valid
|
2133 |
+
py_type = <PyType>_PYTYPE_DICT.get(_pytype)
|
2134 |
+
if py_type is not None:
|
2135 |
+
if py_type.type_check is not None:
|
2136 |
+
py_type.type_check(strval)
|
2137 |
+
_attributes[PYTYPE_ATTRIBUTE] = _pytype
|
2138 |
+
|
2139 |
+
return _makeElement("value", strval, _attributes, nsmap)
|
2140 |
+
|
2141 |
+
|
2142 |
+
################################################################################
|
2143 |
+
# ObjectPath
|
2144 |
+
|
2145 |
+
include "objectpath.pxi"
|
llmeval-env/lib/python3.10/site-packages/lxml/parser.pxi
ADDED
@@ -0,0 +1,1994 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Parsers for XML and HTML
|
2 |
+
|
3 |
+
from lxml.includes cimport xmlparser
|
4 |
+
from lxml.includes cimport htmlparser
|
5 |
+
|
6 |
+
|
7 |
+
class ParseError(LxmlSyntaxError):
|
8 |
+
"""Syntax error while parsing an XML document.
|
9 |
+
|
10 |
+
For compatibility with ElementTree 1.3 and later.
|
11 |
+
"""
|
12 |
+
def __init__(self, message, code, line, column, filename=None):
|
13 |
+
super(_ParseError, self).__init__(message)
|
14 |
+
self.lineno, self.offset = (line, column - 1)
|
15 |
+
self.code = code
|
16 |
+
self.filename = filename
|
17 |
+
|
18 |
+
@property
|
19 |
+
def position(self):
|
20 |
+
return self.lineno, self.offset + 1
|
21 |
+
|
22 |
+
@position.setter
|
23 |
+
def position(self, new_pos):
|
24 |
+
self.lineno, column = new_pos
|
25 |
+
self.offset = column - 1
|
26 |
+
|
27 |
+
cdef object _ParseError = ParseError
|
28 |
+
|
29 |
+
|
30 |
+
class XMLSyntaxError(ParseError):
|
31 |
+
"""Syntax error while parsing an XML document.
|
32 |
+
"""
|
33 |
+
|
34 |
+
cdef class ParserError(LxmlError):
|
35 |
+
"""Internal lxml parser error.
|
36 |
+
"""
|
37 |
+
|
38 |
+
|
39 |
+
@cython.final
|
40 |
+
@cython.internal
|
41 |
+
cdef class _ParserDictionaryContext:
|
42 |
+
# Global parser context to share the string dictionary.
|
43 |
+
#
|
44 |
+
# This class is a delegate singleton!
|
45 |
+
#
|
46 |
+
# It creates _ParserDictionaryContext objects for each thread to keep thread state,
|
47 |
+
# but those must never be used directly. Always stick to using the static
|
48 |
+
# __GLOBAL_PARSER_CONTEXT as defined below the class.
|
49 |
+
#
|
50 |
+
|
51 |
+
cdef tree.xmlDict* _c_dict
|
52 |
+
cdef _BaseParser _default_parser
|
53 |
+
cdef list _implied_parser_contexts
|
54 |
+
|
55 |
+
def __cinit__(self):
|
56 |
+
self._c_dict = NULL
|
57 |
+
self._implied_parser_contexts = []
|
58 |
+
|
59 |
+
def __dealloc__(self):
|
60 |
+
if self._c_dict is not NULL:
|
61 |
+
xmlparser.xmlDictFree(self._c_dict)
|
62 |
+
|
63 |
+
cdef int initMainParserContext(self) except -1:
|
64 |
+
"""Put the global context into the thread dictionary of the main
|
65 |
+
thread. To be called once and only in the main thread."""
|
66 |
+
thread_dict = python.PyThreadState_GetDict()
|
67 |
+
if thread_dict is not NULL:
|
68 |
+
(<dict>thread_dict)["_ParserDictionaryContext"] = self
|
69 |
+
|
70 |
+
cdef _ParserDictionaryContext _findThreadParserContext(self):
|
71 |
+
"Find (or create) the _ParserDictionaryContext object for the current thread"
|
72 |
+
cdef _ParserDictionaryContext context
|
73 |
+
thread_dict = python.PyThreadState_GetDict()
|
74 |
+
if thread_dict is NULL:
|
75 |
+
return self
|
76 |
+
d = <dict>thread_dict
|
77 |
+
result = python.PyDict_GetItem(d, "_ParserDictionaryContext")
|
78 |
+
if result is not NULL:
|
79 |
+
return <object>result
|
80 |
+
context = <_ParserDictionaryContext>_ParserDictionaryContext.__new__(_ParserDictionaryContext)
|
81 |
+
d["_ParserDictionaryContext"] = context
|
82 |
+
return context
|
83 |
+
|
84 |
+
cdef int setDefaultParser(self, _BaseParser parser) except -1:
|
85 |
+
"Set the default parser for the current thread"
|
86 |
+
cdef _ParserDictionaryContext context
|
87 |
+
context = self._findThreadParserContext()
|
88 |
+
context._default_parser = parser
|
89 |
+
|
90 |
+
cdef _BaseParser getDefaultParser(self):
|
91 |
+
"Return (or create) the default parser of the current thread"
|
92 |
+
cdef _ParserDictionaryContext context
|
93 |
+
context = self._findThreadParserContext()
|
94 |
+
if context._default_parser is None:
|
95 |
+
if self._default_parser is None:
|
96 |
+
self._default_parser = __DEFAULT_XML_PARSER._copy()
|
97 |
+
if context is not self:
|
98 |
+
context._default_parser = self._default_parser._copy()
|
99 |
+
return context._default_parser
|
100 |
+
|
101 |
+
cdef tree.xmlDict* _getThreadDict(self, tree.xmlDict* default):
|
102 |
+
"Return the thread-local dict or create a new one if necessary."
|
103 |
+
cdef _ParserDictionaryContext context
|
104 |
+
context = self._findThreadParserContext()
|
105 |
+
if context._c_dict is NULL:
|
106 |
+
# thread dict not yet set up => use default or create a new one
|
107 |
+
if default is not NULL:
|
108 |
+
context._c_dict = default
|
109 |
+
xmlparser.xmlDictReference(default)
|
110 |
+
return default
|
111 |
+
if self._c_dict is NULL:
|
112 |
+
self._c_dict = xmlparser.xmlDictCreate()
|
113 |
+
if context is not self:
|
114 |
+
context._c_dict = xmlparser.xmlDictCreateSub(self._c_dict)
|
115 |
+
return context._c_dict
|
116 |
+
|
117 |
+
cdef int initThreadDictRef(self, tree.xmlDict** c_dict_ref) except -1:
|
118 |
+
c_dict = c_dict_ref[0]
|
119 |
+
c_thread_dict = self._getThreadDict(c_dict)
|
120 |
+
if c_dict is c_thread_dict:
|
121 |
+
return 0
|
122 |
+
if c_dict is not NULL:
|
123 |
+
xmlparser.xmlDictFree(c_dict)
|
124 |
+
c_dict_ref[0] = c_thread_dict
|
125 |
+
xmlparser.xmlDictReference(c_thread_dict)
|
126 |
+
|
127 |
+
cdef int initParserDict(self, xmlparser.xmlParserCtxt* pctxt) except -1:
|
128 |
+
"Assure we always use the same string dictionary."
|
129 |
+
self.initThreadDictRef(&pctxt.dict)
|
130 |
+
pctxt.dictNames = 1
|
131 |
+
|
132 |
+
cdef int initXPathParserDict(self, xpath.xmlXPathContext* pctxt) except -1:
|
133 |
+
"Assure we always use the same string dictionary."
|
134 |
+
self.initThreadDictRef(&pctxt.dict)
|
135 |
+
|
136 |
+
cdef int initDocDict(self, xmlDoc* result) except -1:
|
137 |
+
"Store dict of last object parsed if no shared dict yet"
|
138 |
+
# XXX We also free the result dict here if there already was one.
|
139 |
+
# This case should only occur for new documents with empty dicts,
|
140 |
+
# otherwise we'd free data that's in use => segfault
|
141 |
+
self.initThreadDictRef(&result.dict)
|
142 |
+
|
143 |
+
cdef _ParserContext findImpliedContext(self):
|
144 |
+
"""Return any current implied xml parser context for the current
|
145 |
+
thread. This is used when the resolver functions are called
|
146 |
+
with an xmlParserCtxt that was generated from within libxml2
|
147 |
+
(i.e. without a _ParserContext) - which happens when parsing
|
148 |
+
schema and xinclude external references."""
|
149 |
+
cdef _ParserDictionaryContext context
|
150 |
+
cdef _ParserContext implied_context
|
151 |
+
|
152 |
+
# see if we have a current implied parser
|
153 |
+
context = self._findThreadParserContext()
|
154 |
+
if context._implied_parser_contexts:
|
155 |
+
implied_context = context._implied_parser_contexts[-1]
|
156 |
+
return implied_context
|
157 |
+
return None
|
158 |
+
|
159 |
+
cdef int pushImpliedContextFromParser(self, _BaseParser parser) except -1:
|
160 |
+
"Push a new implied context object taken from the parser."
|
161 |
+
if parser is not None:
|
162 |
+
self.pushImpliedContext(parser._getParserContext())
|
163 |
+
else:
|
164 |
+
self.pushImpliedContext(None)
|
165 |
+
|
166 |
+
cdef int pushImpliedContext(self, _ParserContext parser_context) except -1:
|
167 |
+
"Push a new implied context object."
|
168 |
+
cdef _ParserDictionaryContext context
|
169 |
+
context = self._findThreadParserContext()
|
170 |
+
context._implied_parser_contexts.append(parser_context)
|
171 |
+
|
172 |
+
cdef int popImpliedContext(self) except -1:
|
173 |
+
"Pop the current implied context object."
|
174 |
+
cdef _ParserDictionaryContext context
|
175 |
+
context = self._findThreadParserContext()
|
176 |
+
context._implied_parser_contexts.pop()
|
177 |
+
|
178 |
+
cdef _ParserDictionaryContext __GLOBAL_PARSER_CONTEXT = _ParserDictionaryContext()
|
179 |
+
__GLOBAL_PARSER_CONTEXT.initMainParserContext()
|
180 |
+
|
181 |
+
############################################################
|
182 |
+
## support for Python unicode I/O
|
183 |
+
############################################################
|
184 |
+
|
185 |
+
# name of Python Py_UNICODE encoding as known to libxml2
|
186 |
+
cdef const_char* _PY_UNICODE_ENCODING = NULL
|
187 |
+
|
188 |
+
cdef int _setupPythonUnicode() except -1:
|
189 |
+
"""Sets _PY_UNICODE_ENCODING to the internal encoding name of Python unicode
|
190 |
+
strings if libxml2 supports reading native Python unicode. This depends
|
191 |
+
on iconv and the local Python installation, so we simply check if we find
|
192 |
+
a matching encoding handler.
|
193 |
+
"""
|
194 |
+
cdef tree.xmlCharEncodingHandler* enchandler
|
195 |
+
cdef Py_ssize_t l
|
196 |
+
cdef const_char* enc
|
197 |
+
cdef Py_UNICODE *uchars = [c'<', c't', c'e', c's', c't', c'/', c'>']
|
198 |
+
cdef const_xmlChar* buffer = <const_xmlChar*>uchars
|
199 |
+
# apparently, libxml2 can't detect UTF-16 on some systems
|
200 |
+
if (buffer[0] == c'<' and buffer[1] == c'\0' and
|
201 |
+
buffer[2] == c't' and buffer[3] == c'\0'):
|
202 |
+
enc = "UTF-16LE"
|
203 |
+
elif (buffer[0] == c'\0' and buffer[1] == c'<' and
|
204 |
+
buffer[2] == c'\0' and buffer[3] == c't'):
|
205 |
+
enc = "UTF-16BE"
|
206 |
+
else:
|
207 |
+
# let libxml2 give it a try
|
208 |
+
enc = _findEncodingName(buffer, sizeof(Py_UNICODE) * 7)
|
209 |
+
if enc is NULL:
|
210 |
+
# not my fault, it's YOUR broken system :)
|
211 |
+
return 0
|
212 |
+
enchandler = tree.xmlFindCharEncodingHandler(enc)
|
213 |
+
if enchandler is not NULL:
|
214 |
+
global _PY_UNICODE_ENCODING
|
215 |
+
tree.xmlCharEncCloseFunc(enchandler)
|
216 |
+
_PY_UNICODE_ENCODING = enc
|
217 |
+
return 0
|
218 |
+
|
219 |
+
cdef const_char* _findEncodingName(const_xmlChar* buffer, int size):
|
220 |
+
"Work around bug in libxml2: find iconv name of encoding on our own."
|
221 |
+
cdef tree.xmlCharEncoding enc
|
222 |
+
enc = tree.xmlDetectCharEncoding(buffer, size)
|
223 |
+
if enc == tree.XML_CHAR_ENCODING_UTF16LE:
|
224 |
+
if size >= 4 and (buffer[0] == <const_xmlChar> b'\xFF' and
|
225 |
+
buffer[1] == <const_xmlChar> b'\xFE' and
|
226 |
+
buffer[2] == 0 and buffer[3] == 0):
|
227 |
+
return "UTF-32LE" # according to BOM
|
228 |
+
else:
|
229 |
+
return "UTF-16LE"
|
230 |
+
elif enc == tree.XML_CHAR_ENCODING_UTF16BE:
|
231 |
+
return "UTF-16BE"
|
232 |
+
elif enc == tree.XML_CHAR_ENCODING_UCS4LE:
|
233 |
+
return "UCS-4LE"
|
234 |
+
elif enc == tree.XML_CHAR_ENCODING_UCS4BE:
|
235 |
+
return "UCS-4BE"
|
236 |
+
elif enc == tree.XML_CHAR_ENCODING_NONE:
|
237 |
+
return NULL
|
238 |
+
else:
|
239 |
+
# returns a constant char*, no need to free it
|
240 |
+
return tree.xmlGetCharEncodingName(enc)
|
241 |
+
|
242 |
+
# Python 3.12 removed support for "Py_UNICODE".
|
243 |
+
if python.PY_VERSION_HEX < 0x030C0000:
|
244 |
+
_setupPythonUnicode()
|
245 |
+
|
246 |
+
|
247 |
+
cdef unicode _find_PyUCS4EncodingName():
|
248 |
+
"""
|
249 |
+
Find a suitable encoding for Py_UCS4 PyUnicode strings in libxml2.
|
250 |
+
"""
|
251 |
+
ustring = "<xml>\U0001F92A</xml>"
|
252 |
+
cdef const xmlChar* buffer = <const xmlChar*> python.PyUnicode_DATA(ustring)
|
253 |
+
cdef Py_ssize_t py_buffer_len = python.PyUnicode_GET_LENGTH(ustring)
|
254 |
+
|
255 |
+
encoding_name = ''
|
256 |
+
cdef tree.xmlCharEncoding enc = tree.xmlDetectCharEncoding(buffer, py_buffer_len)
|
257 |
+
enchandler = tree.xmlGetCharEncodingHandler(enc)
|
258 |
+
if enchandler is not NULL:
|
259 |
+
try:
|
260 |
+
if enchandler.name:
|
261 |
+
encoding_name = enchandler.name.decode('UTF-8')
|
262 |
+
finally:
|
263 |
+
tree.xmlCharEncCloseFunc(enchandler)
|
264 |
+
else:
|
265 |
+
c_name = tree.xmlGetCharEncodingName(enc)
|
266 |
+
if c_name:
|
267 |
+
encoding_name = c_name.decode('UTF-8')
|
268 |
+
|
269 |
+
|
270 |
+
if encoding_name and not encoding_name.endswith('LE') and not encoding_name.endswith('BE'):
|
271 |
+
encoding_name += 'BE' if python.PY_BIG_ENDIAN else 'LE'
|
272 |
+
return encoding_name or None
|
273 |
+
|
274 |
+
_pyucs4_encoding_name = _find_PyUCS4EncodingName()
|
275 |
+
|
276 |
+
|
277 |
+
############################################################
|
278 |
+
## support for file-like objects
|
279 |
+
############################################################
|
280 |
+
|
281 |
+
@cython.final
|
282 |
+
@cython.internal
|
283 |
+
cdef class _FileReaderContext:
|
284 |
+
cdef object _filelike
|
285 |
+
cdef object _encoding
|
286 |
+
cdef object _url
|
287 |
+
cdef object _bytes
|
288 |
+
cdef _ExceptionContext _exc_context
|
289 |
+
cdef Py_ssize_t _bytes_read
|
290 |
+
cdef char* _c_url
|
291 |
+
cdef bint _close_file_after_read
|
292 |
+
|
293 |
+
def __cinit__(self, filelike, exc_context not None, url, encoding=None, bint close_file=False):
|
294 |
+
self._exc_context = exc_context
|
295 |
+
self._filelike = filelike
|
296 |
+
self._close_file_after_read = close_file
|
297 |
+
self._encoding = encoding
|
298 |
+
if url is None:
|
299 |
+
self._c_url = NULL
|
300 |
+
else:
|
301 |
+
url = _encodeFilename(url)
|
302 |
+
self._c_url = _cstr(url)
|
303 |
+
self._url = url
|
304 |
+
self._bytes = b''
|
305 |
+
self._bytes_read = 0
|
306 |
+
|
307 |
+
cdef _close_file(self):
|
308 |
+
if self._filelike is None or not self._close_file_after_read:
|
309 |
+
return
|
310 |
+
try:
|
311 |
+
close = self._filelike.close
|
312 |
+
except AttributeError:
|
313 |
+
close = None
|
314 |
+
finally:
|
315 |
+
self._filelike = None
|
316 |
+
if close is not None:
|
317 |
+
close()
|
318 |
+
|
319 |
+
cdef xmlparser.xmlParserInputBuffer* _createParserInputBuffer(self) noexcept:
|
320 |
+
cdef xmlparser.xmlParserInputBuffer* c_buffer = xmlparser.xmlAllocParserInputBuffer(0)
|
321 |
+
if c_buffer:
|
322 |
+
c_buffer.readcallback = _readFilelikeParser
|
323 |
+
c_buffer.context = <python.PyObject*> self
|
324 |
+
return c_buffer
|
325 |
+
|
326 |
+
cdef xmlparser.xmlParserInput* _createParserInput(
|
327 |
+
self, xmlparser.xmlParserCtxt* ctxt) noexcept:
|
328 |
+
cdef xmlparser.xmlParserInputBuffer* c_buffer = self._createParserInputBuffer()
|
329 |
+
if not c_buffer:
|
330 |
+
return NULL
|
331 |
+
return xmlparser.xmlNewIOInputStream(ctxt, c_buffer, 0)
|
332 |
+
|
333 |
+
cdef tree.xmlDtd* _readDtd(self) noexcept:
|
334 |
+
cdef xmlparser.xmlParserInputBuffer* c_buffer = self._createParserInputBuffer()
|
335 |
+
if not c_buffer:
|
336 |
+
return NULL
|
337 |
+
with nogil:
|
338 |
+
return xmlparser.xmlIOParseDTD(NULL, c_buffer, 0)
|
339 |
+
|
340 |
+
cdef xmlDoc* _readDoc(self, xmlparser.xmlParserCtxt* ctxt, int options) noexcept:
|
341 |
+
cdef xmlDoc* result
|
342 |
+
cdef void* c_callback_context = <python.PyObject*> self
|
343 |
+
cdef char* c_encoding = _cstr(self._encoding) if self._encoding is not None else NULL
|
344 |
+
|
345 |
+
orig_options = ctxt.options
|
346 |
+
with nogil:
|
347 |
+
if ctxt.html:
|
348 |
+
result = htmlparser.htmlCtxtReadIO(
|
349 |
+
ctxt, _readFilelikeParser, NULL, c_callback_context,
|
350 |
+
self._c_url, c_encoding, options)
|
351 |
+
if result is not NULL:
|
352 |
+
if _fixHtmlDictNames(ctxt.dict, result) < 0:
|
353 |
+
tree.xmlFreeDoc(result)
|
354 |
+
result = NULL
|
355 |
+
else:
|
356 |
+
result = xmlparser.xmlCtxtReadIO(
|
357 |
+
ctxt, _readFilelikeParser, NULL, c_callback_context,
|
358 |
+
self._c_url, c_encoding, options)
|
359 |
+
ctxt.options = orig_options # work around libxml2 problem
|
360 |
+
|
361 |
+
try:
|
362 |
+
self._close_file()
|
363 |
+
except:
|
364 |
+
self._exc_context._store_raised()
|
365 |
+
finally:
|
366 |
+
return result # swallow any exceptions
|
367 |
+
|
368 |
+
cdef int copyToBuffer(self, char* c_buffer, int c_requested) noexcept:
|
369 |
+
cdef int c_byte_count = 0
|
370 |
+
cdef char* c_start
|
371 |
+
cdef Py_ssize_t byte_count, remaining
|
372 |
+
if self._bytes_read < 0:
|
373 |
+
return 0
|
374 |
+
try:
|
375 |
+
byte_count = python.PyBytes_GET_SIZE(self._bytes)
|
376 |
+
remaining = byte_count - self._bytes_read
|
377 |
+
while c_requested > remaining:
|
378 |
+
c_start = _cstr(self._bytes) + self._bytes_read
|
379 |
+
cstring_h.memcpy(c_buffer, c_start, remaining)
|
380 |
+
c_byte_count += remaining
|
381 |
+
c_buffer += remaining
|
382 |
+
c_requested -= remaining
|
383 |
+
|
384 |
+
self._bytes = self._filelike.read(c_requested)
|
385 |
+
if not isinstance(self._bytes, bytes):
|
386 |
+
if isinstance(self._bytes, unicode):
|
387 |
+
if self._encoding is None:
|
388 |
+
self._bytes = (<unicode>self._bytes).encode('utf8')
|
389 |
+
else:
|
390 |
+
self._bytes = python.PyUnicode_AsEncodedString(
|
391 |
+
self._bytes, _cstr(self._encoding), NULL)
|
392 |
+
else:
|
393 |
+
self._close_file()
|
394 |
+
raise TypeError, \
|
395 |
+
"reading from file-like objects must return byte strings or unicode strings"
|
396 |
+
|
397 |
+
remaining = python.PyBytes_GET_SIZE(self._bytes)
|
398 |
+
if remaining == 0:
|
399 |
+
self._bytes_read = -1
|
400 |
+
self._close_file()
|
401 |
+
return c_byte_count
|
402 |
+
self._bytes_read = 0
|
403 |
+
|
404 |
+
if c_requested > 0:
|
405 |
+
c_start = _cstr(self._bytes) + self._bytes_read
|
406 |
+
cstring_h.memcpy(c_buffer, c_start, c_requested)
|
407 |
+
c_byte_count += c_requested
|
408 |
+
self._bytes_read += c_requested
|
409 |
+
except:
|
410 |
+
c_byte_count = -1
|
411 |
+
self._exc_context._store_raised()
|
412 |
+
try:
|
413 |
+
self._close_file()
|
414 |
+
except:
|
415 |
+
self._exc_context._store_raised()
|
416 |
+
finally:
|
417 |
+
return c_byte_count # swallow any exceptions
|
418 |
+
|
419 |
+
cdef int _readFilelikeParser(void* ctxt, char* c_buffer, int c_size) noexcept with gil:
|
420 |
+
return (<_FileReaderContext>ctxt).copyToBuffer(c_buffer, c_size)
|
421 |
+
|
422 |
+
cdef int _readFileParser(void* ctxt, char* c_buffer, int c_size) noexcept nogil:
|
423 |
+
return stdio.fread(c_buffer, 1, c_size, <stdio.FILE*>ctxt)
|
424 |
+
|
425 |
+
############################################################
|
426 |
+
## support for custom document loaders
|
427 |
+
############################################################
|
428 |
+
|
429 |
+
cdef xmlparser.xmlParserInput* _local_resolver(const_char* c_url, const_char* c_pubid,
|
430 |
+
xmlparser.xmlParserCtxt* c_context) noexcept with gil:
|
431 |
+
cdef _ResolverContext context
|
432 |
+
cdef xmlparser.xmlParserInput* c_input
|
433 |
+
cdef _InputDocument doc_ref
|
434 |
+
cdef _FileReaderContext file_context
|
435 |
+
# if there is no _ParserContext associated with the xmlParserCtxt
|
436 |
+
# passed, check to see if the thread state object has an implied
|
437 |
+
# context.
|
438 |
+
if c_context._private is not NULL:
|
439 |
+
context = <_ResolverContext>c_context._private
|
440 |
+
else:
|
441 |
+
context = __GLOBAL_PARSER_CONTEXT.findImpliedContext()
|
442 |
+
|
443 |
+
if context is None:
|
444 |
+
if __DEFAULT_ENTITY_LOADER is NULL:
|
445 |
+
return NULL
|
446 |
+
with nogil:
|
447 |
+
# free the GIL as we might do serious I/O here (e.g. HTTP)
|
448 |
+
c_input = __DEFAULT_ENTITY_LOADER(c_url, c_pubid, c_context)
|
449 |
+
return c_input
|
450 |
+
|
451 |
+
try:
|
452 |
+
if c_url is NULL:
|
453 |
+
url = None
|
454 |
+
else:
|
455 |
+
# parsing a related document (DTD etc.) => UTF-8 encoded URL?
|
456 |
+
url = _decodeFilename(<const_xmlChar*>c_url)
|
457 |
+
if c_pubid is NULL:
|
458 |
+
pubid = None
|
459 |
+
else:
|
460 |
+
pubid = funicode(<const_xmlChar*>c_pubid) # always UTF-8
|
461 |
+
|
462 |
+
doc_ref = context._resolvers.resolve(url, pubid, context)
|
463 |
+
except:
|
464 |
+
context._store_raised()
|
465 |
+
return NULL
|
466 |
+
|
467 |
+
if doc_ref is not None:
|
468 |
+
if doc_ref._type == PARSER_DATA_STRING:
|
469 |
+
data = doc_ref._data_bytes
|
470 |
+
filename = doc_ref._filename
|
471 |
+
if not filename:
|
472 |
+
filename = None
|
473 |
+
elif not isinstance(filename, bytes):
|
474 |
+
# most likely a text URL
|
475 |
+
filename = filename.encode('utf8')
|
476 |
+
if not isinstance(filename, bytes):
|
477 |
+
filename = None
|
478 |
+
|
479 |
+
c_input = xmlparser.xmlNewInputStream(c_context)
|
480 |
+
if c_input is not NULL:
|
481 |
+
if filename is not None:
|
482 |
+
c_input.filename = <char *>tree.xmlStrdup(_xcstr(filename))
|
483 |
+
c_input.base = _xcstr(data)
|
484 |
+
c_input.length = python.PyBytes_GET_SIZE(data)
|
485 |
+
c_input.cur = c_input.base
|
486 |
+
c_input.end = c_input.base + c_input.length
|
487 |
+
elif doc_ref._type == PARSER_DATA_FILENAME:
|
488 |
+
data = None
|
489 |
+
c_filename = _cstr(doc_ref._filename)
|
490 |
+
with nogil:
|
491 |
+
# free the GIL as we might do serious I/O here
|
492 |
+
c_input = xmlparser.xmlNewInputFromFile(
|
493 |
+
c_context, c_filename)
|
494 |
+
elif doc_ref._type == PARSER_DATA_FILE:
|
495 |
+
file_context = _FileReaderContext(doc_ref._file, context, url,
|
496 |
+
None, doc_ref._close_file)
|
497 |
+
c_input = file_context._createParserInput(c_context)
|
498 |
+
data = file_context
|
499 |
+
else:
|
500 |
+
data = None
|
501 |
+
c_input = NULL
|
502 |
+
|
503 |
+
if data is not None:
|
504 |
+
context._storage.add(data)
|
505 |
+
if c_input is not NULL:
|
506 |
+
return c_input
|
507 |
+
|
508 |
+
if __DEFAULT_ENTITY_LOADER is NULL:
|
509 |
+
return NULL
|
510 |
+
|
511 |
+
with nogil:
|
512 |
+
# free the GIL as we might do serious I/O here (e.g. HTTP)
|
513 |
+
c_input = __DEFAULT_ENTITY_LOADER(c_url, c_pubid, c_context)
|
514 |
+
return c_input
|
515 |
+
|
516 |
+
cdef xmlparser.xmlExternalEntityLoader __DEFAULT_ENTITY_LOADER
|
517 |
+
__DEFAULT_ENTITY_LOADER = xmlparser.xmlGetExternalEntityLoader()
|
518 |
+
|
519 |
+
|
520 |
+
cdef xmlparser.xmlExternalEntityLoader _register_document_loader() noexcept nogil:
|
521 |
+
cdef xmlparser.xmlExternalEntityLoader old = xmlparser.xmlGetExternalEntityLoader()
|
522 |
+
xmlparser.xmlSetExternalEntityLoader(<xmlparser.xmlExternalEntityLoader>_local_resolver)
|
523 |
+
return old
|
524 |
+
|
525 |
+
cdef void _reset_document_loader(xmlparser.xmlExternalEntityLoader old) noexcept nogil:
|
526 |
+
xmlparser.xmlSetExternalEntityLoader(old)
|
527 |
+
|
528 |
+
|
529 |
+
############################################################
|
530 |
+
## Parsers
|
531 |
+
############################################################
|
532 |
+
|
533 |
+
@cython.no_gc_clear # May have to call "self._validator.disconnect()" on dealloc.
|
534 |
+
@cython.internal
|
535 |
+
cdef class _ParserContext(_ResolverContext):
|
536 |
+
cdef _ErrorLog _error_log
|
537 |
+
cdef _ParserSchemaValidationContext _validator
|
538 |
+
cdef xmlparser.xmlParserCtxt* _c_ctxt
|
539 |
+
cdef xmlparser.xmlExternalEntityLoader _orig_loader
|
540 |
+
cdef python.PyThread_type_lock _lock
|
541 |
+
cdef _Document _doc
|
542 |
+
cdef bint _collect_ids
|
543 |
+
|
544 |
+
def __cinit__(self):
|
545 |
+
self._c_ctxt = NULL
|
546 |
+
self._collect_ids = True
|
547 |
+
if not config.ENABLE_THREADING:
|
548 |
+
self._lock = NULL
|
549 |
+
else:
|
550 |
+
self._lock = python.PyThread_allocate_lock()
|
551 |
+
self._error_log = _ErrorLog()
|
552 |
+
|
553 |
+
def __dealloc__(self):
|
554 |
+
if config.ENABLE_THREADING and self._lock is not NULL:
|
555 |
+
python.PyThread_free_lock(self._lock)
|
556 |
+
self._lock = NULL
|
557 |
+
if self._c_ctxt is not NULL:
|
558 |
+
if <void*>self._validator is not NULL and self._validator is not None:
|
559 |
+
# If the parser was not closed correctly (e.g. interrupted iterparse()),
|
560 |
+
# and the schema validator wasn't freed and cleaned up yet, the libxml2 SAX
|
561 |
+
# validator plug might still be in place, which will make xmlFreeParserCtxt()
|
562 |
+
# crash when trying to xmlFree() a static SAX handler.
|
563 |
+
# Thus, make sure we disconnect the handler interceptor here at the latest.
|
564 |
+
self._validator.disconnect()
|
565 |
+
xmlparser.xmlFreeParserCtxt(self._c_ctxt)
|
566 |
+
|
567 |
+
cdef _ParserContext _copy(self):
|
568 |
+
cdef _ParserContext context
|
569 |
+
context = self.__class__()
|
570 |
+
context._collect_ids = self._collect_ids
|
571 |
+
context._validator = self._validator.copy()
|
572 |
+
_initParserContext(context, self._resolvers._copy(), NULL)
|
573 |
+
return context
|
574 |
+
|
575 |
+
cdef void _initParserContext(self, xmlparser.xmlParserCtxt* c_ctxt) noexcept:
|
576 |
+
self._c_ctxt = c_ctxt
|
577 |
+
c_ctxt._private = <void*>self
|
578 |
+
|
579 |
+
cdef void _resetParserContext(self) noexcept:
|
580 |
+
if self._c_ctxt is not NULL:
|
581 |
+
if self._c_ctxt.html:
|
582 |
+
htmlparser.htmlCtxtReset(self._c_ctxt)
|
583 |
+
self._c_ctxt.disableSAX = 0 # work around bug in libxml2
|
584 |
+
else:
|
585 |
+
xmlparser.xmlClearParserCtxt(self._c_ctxt)
|
586 |
+
# work around bug in libxml2 [2.9.10 .. 2.9.14]:
|
587 |
+
# https://gitlab.gnome.org/GNOME/libxml2/-/issues/378
|
588 |
+
self._c_ctxt.nsNr = 0
|
589 |
+
|
590 |
+
cdef int prepare(self, bint set_document_loader=True) except -1:
|
591 |
+
cdef int result
|
592 |
+
if config.ENABLE_THREADING and self._lock is not NULL:
|
593 |
+
with nogil:
|
594 |
+
result = python.PyThread_acquire_lock(
|
595 |
+
self._lock, python.WAIT_LOCK)
|
596 |
+
if result == 0:
|
597 |
+
raise ParserError, "parser locking failed"
|
598 |
+
self._error_log.clear()
|
599 |
+
self._doc = None
|
600 |
+
# Need a cast here because older libxml2 releases do not use 'const' in the functype.
|
601 |
+
self._c_ctxt.sax.serror = <xmlerror.xmlStructuredErrorFunc> _receiveParserError
|
602 |
+
self._orig_loader = _register_document_loader() if set_document_loader else NULL
|
603 |
+
if self._validator is not None:
|
604 |
+
self._validator.connect(self._c_ctxt, self._error_log)
|
605 |
+
return 0
|
606 |
+
|
607 |
+
cdef int cleanup(self) except -1:
|
608 |
+
if self._orig_loader is not NULL:
|
609 |
+
_reset_document_loader(self._orig_loader)
|
610 |
+
try:
|
611 |
+
if self._validator is not None:
|
612 |
+
self._validator.disconnect()
|
613 |
+
self._resetParserContext()
|
614 |
+
self.clear()
|
615 |
+
self._doc = None
|
616 |
+
self._c_ctxt.sax.serror = NULL
|
617 |
+
finally:
|
618 |
+
if config.ENABLE_THREADING and self._lock is not NULL:
|
619 |
+
python.PyThread_release_lock(self._lock)
|
620 |
+
return 0
|
621 |
+
|
622 |
+
cdef object _handleParseResult(self, _BaseParser parser,
|
623 |
+
xmlDoc* result, filename):
|
624 |
+
c_doc = self._handleParseResultDoc(parser, result, filename)
|
625 |
+
if self._doc is not None and self._doc._c_doc is c_doc:
|
626 |
+
return self._doc
|
627 |
+
else:
|
628 |
+
return _documentFactory(c_doc, parser)
|
629 |
+
|
630 |
+
cdef xmlDoc* _handleParseResultDoc(self, _BaseParser parser,
|
631 |
+
xmlDoc* result, filename) except NULL:
|
632 |
+
recover = parser._parse_options & xmlparser.XML_PARSE_RECOVER
|
633 |
+
return _handleParseResult(self, self._c_ctxt, result,
|
634 |
+
filename, recover,
|
635 |
+
free_doc=self._doc is None)
|
636 |
+
|
637 |
+
cdef _initParserContext(_ParserContext context,
|
638 |
+
_ResolverRegistry resolvers,
|
639 |
+
xmlparser.xmlParserCtxt* c_ctxt):
|
640 |
+
_initResolverContext(context, resolvers)
|
641 |
+
if c_ctxt is not NULL:
|
642 |
+
context._initParserContext(c_ctxt)
|
643 |
+
|
644 |
+
cdef void _forwardParserError(xmlparser.xmlParserCtxt* _parser_context, const xmlerror.xmlError* error) noexcept with gil:
|
645 |
+
(<_ParserContext>_parser_context._private)._error_log._receive(error)
|
646 |
+
|
647 |
+
cdef void _receiveParserError(void* c_context, const xmlerror.xmlError* error) noexcept nogil:
|
648 |
+
if __DEBUG:
|
649 |
+
if c_context is NULL or (<xmlparser.xmlParserCtxt*>c_context)._private is NULL:
|
650 |
+
_forwardError(NULL, error)
|
651 |
+
else:
|
652 |
+
_forwardParserError(<xmlparser.xmlParserCtxt*>c_context, error)
|
653 |
+
|
654 |
+
cdef int _raiseParseError(xmlparser.xmlParserCtxt* ctxt, filename,
|
655 |
+
_ErrorLog error_log) except -1:
|
656 |
+
if filename is not None and \
|
657 |
+
ctxt.lastError.domain == xmlerror.XML_FROM_IO:
|
658 |
+
if isinstance(filename, bytes):
|
659 |
+
filename = _decodeFilenameWithLength(
|
660 |
+
<bytes>filename, len(<bytes>filename))
|
661 |
+
if ctxt.lastError.message is not NULL:
|
662 |
+
try:
|
663 |
+
message = ctxt.lastError.message.decode('utf-8')
|
664 |
+
except UnicodeDecodeError:
|
665 |
+
# the filename may be in there => play it safe
|
666 |
+
message = ctxt.lastError.message.decode('iso8859-1')
|
667 |
+
message = f"Error reading file '{filename}': {message.strip()}"
|
668 |
+
else:
|
669 |
+
message = f"Error reading '{filename}'"
|
670 |
+
raise IOError, message
|
671 |
+
elif error_log:
|
672 |
+
raise error_log._buildParseException(
|
673 |
+
XMLSyntaxError, "Document is not well formed")
|
674 |
+
elif ctxt.lastError.message is not NULL:
|
675 |
+
message = ctxt.lastError.message.strip()
|
676 |
+
code = ctxt.lastError.code
|
677 |
+
line = ctxt.lastError.line
|
678 |
+
column = ctxt.lastError.int2
|
679 |
+
if ctxt.lastError.line > 0:
|
680 |
+
message = f"line {line}: {message}"
|
681 |
+
raise XMLSyntaxError(message, code, line, column, filename)
|
682 |
+
else:
|
683 |
+
raise XMLSyntaxError(None, xmlerror.XML_ERR_INTERNAL_ERROR, 0, 0,
|
684 |
+
filename)
|
685 |
+
|
686 |
+
cdef xmlDoc* _handleParseResult(_ParserContext context,
|
687 |
+
xmlparser.xmlParserCtxt* c_ctxt,
|
688 |
+
xmlDoc* result, filename,
|
689 |
+
bint recover, bint free_doc) except NULL:
|
690 |
+
cdef bint well_formed
|
691 |
+
if result is not NULL:
|
692 |
+
__GLOBAL_PARSER_CONTEXT.initDocDict(result)
|
693 |
+
|
694 |
+
if c_ctxt.myDoc is not NULL:
|
695 |
+
if c_ctxt.myDoc is not result:
|
696 |
+
__GLOBAL_PARSER_CONTEXT.initDocDict(c_ctxt.myDoc)
|
697 |
+
tree.xmlFreeDoc(c_ctxt.myDoc)
|
698 |
+
c_ctxt.myDoc = NULL
|
699 |
+
|
700 |
+
if result is not NULL:
|
701 |
+
if (context._validator is not None and
|
702 |
+
not context._validator.isvalid()):
|
703 |
+
well_formed = 0 # actually not 'valid', but anyway ...
|
704 |
+
elif (not c_ctxt.wellFormed and not c_ctxt.html and
|
705 |
+
c_ctxt.charset == tree.XML_CHAR_ENCODING_8859_1 and
|
706 |
+
[1 for error in context._error_log
|
707 |
+
if error.type == ErrorTypes.ERR_INVALID_CHAR]):
|
708 |
+
# An encoding error occurred and libxml2 switched from UTF-8
|
709 |
+
# input to (undecoded) Latin-1, at some arbitrary point in the
|
710 |
+
# document. Better raise an error than allowing for a broken
|
711 |
+
# tree with mixed encodings. This is fixed in libxml2 2.12.
|
712 |
+
well_formed = 0
|
713 |
+
elif recover or (c_ctxt.wellFormed and
|
714 |
+
c_ctxt.lastError.level < xmlerror.XML_ERR_ERROR):
|
715 |
+
well_formed = 1
|
716 |
+
elif not c_ctxt.replaceEntities and not c_ctxt.validate \
|
717 |
+
and context is not None:
|
718 |
+
# in this mode, we ignore errors about undefined entities
|
719 |
+
for error in context._error_log.filter_from_errors():
|
720 |
+
if error.type != ErrorTypes.WAR_UNDECLARED_ENTITY and \
|
721 |
+
error.type != ErrorTypes.ERR_UNDECLARED_ENTITY:
|
722 |
+
well_formed = 0
|
723 |
+
break
|
724 |
+
else:
|
725 |
+
well_formed = 1
|
726 |
+
else:
|
727 |
+
well_formed = 0
|
728 |
+
|
729 |
+
if not well_formed:
|
730 |
+
if free_doc:
|
731 |
+
tree.xmlFreeDoc(result)
|
732 |
+
result = NULL
|
733 |
+
|
734 |
+
if context is not None and context._has_raised():
|
735 |
+
if result is not NULL:
|
736 |
+
if free_doc:
|
737 |
+
tree.xmlFreeDoc(result)
|
738 |
+
result = NULL
|
739 |
+
context._raise_if_stored()
|
740 |
+
|
741 |
+
if result is NULL:
|
742 |
+
if context is not None:
|
743 |
+
_raiseParseError(c_ctxt, filename, context._error_log)
|
744 |
+
else:
|
745 |
+
_raiseParseError(c_ctxt, filename, None)
|
746 |
+
else:
|
747 |
+
if result.URL is NULL and filename is not None:
|
748 |
+
result.URL = tree.xmlStrdup(_xcstr(filename))
|
749 |
+
if result.encoding is NULL:
|
750 |
+
result.encoding = tree.xmlStrdup(<unsigned char*>"UTF-8")
|
751 |
+
|
752 |
+
if context._validator is not None and \
|
753 |
+
context._validator._add_default_attributes:
|
754 |
+
# we currently need to do this here as libxml2 does not
|
755 |
+
# support inserting default attributes during parse-time
|
756 |
+
# validation
|
757 |
+
context._validator.inject_default_attributes(result)
|
758 |
+
|
759 |
+
return result
|
760 |
+
|
761 |
+
cdef int _fixHtmlDictNames(tree.xmlDict* c_dict, xmlDoc* c_doc) noexcept nogil:
|
762 |
+
cdef xmlNode* c_node
|
763 |
+
if c_doc is NULL:
|
764 |
+
return 0
|
765 |
+
c_node = c_doc.children
|
766 |
+
tree.BEGIN_FOR_EACH_ELEMENT_FROM(<xmlNode*>c_doc, c_node, 1)
|
767 |
+
if c_node.type == tree.XML_ELEMENT_NODE:
|
768 |
+
if _fixHtmlDictNodeNames(c_dict, c_node) < 0:
|
769 |
+
return -1
|
770 |
+
tree.END_FOR_EACH_ELEMENT_FROM(c_node)
|
771 |
+
return 0
|
772 |
+
|
773 |
+
cdef int _fixHtmlDictSubtreeNames(tree.xmlDict* c_dict, xmlDoc* c_doc,
|
774 |
+
xmlNode* c_start_node) noexcept nogil:
|
775 |
+
"""
|
776 |
+
Move names to the dict, iterating in document order, starting at
|
777 |
+
c_start_node. This is used in incremental parsing after each chunk.
|
778 |
+
"""
|
779 |
+
cdef xmlNode* c_node
|
780 |
+
if not c_doc:
|
781 |
+
return 0
|
782 |
+
if not c_start_node:
|
783 |
+
return _fixHtmlDictNames(c_dict, c_doc)
|
784 |
+
c_node = c_start_node
|
785 |
+
tree.BEGIN_FOR_EACH_ELEMENT_FROM(<xmlNode*>c_doc, c_node, 1)
|
786 |
+
if c_node.type == tree.XML_ELEMENT_NODE:
|
787 |
+
if _fixHtmlDictNodeNames(c_dict, c_node) < 0:
|
788 |
+
return -1
|
789 |
+
tree.END_FOR_EACH_ELEMENT_FROM(c_node)
|
790 |
+
return 0
|
791 |
+
|
792 |
+
cdef inline int _fixHtmlDictNodeNames(tree.xmlDict* c_dict,
|
793 |
+
xmlNode* c_node) noexcept nogil:
|
794 |
+
cdef xmlNode* c_attr
|
795 |
+
c_name = tree.xmlDictLookup(c_dict, c_node.name, -1)
|
796 |
+
if c_name is NULL:
|
797 |
+
return -1
|
798 |
+
if c_name is not c_node.name:
|
799 |
+
tree.xmlFree(<char*>c_node.name)
|
800 |
+
c_node.name = c_name
|
801 |
+
c_attr = <xmlNode*>c_node.properties
|
802 |
+
while c_attr is not NULL:
|
803 |
+
c_name = tree.xmlDictLookup(c_dict, c_attr.name, -1)
|
804 |
+
if c_name is NULL:
|
805 |
+
return -1
|
806 |
+
if c_name is not c_attr.name:
|
807 |
+
tree.xmlFree(<char*>c_attr.name)
|
808 |
+
c_attr.name = c_name
|
809 |
+
c_attr = c_attr.next
|
810 |
+
return 0
|
811 |
+
|
812 |
+
|
813 |
+
@cython.internal
|
814 |
+
cdef class _BaseParser:
|
815 |
+
cdef ElementClassLookup _class_lookup
|
816 |
+
cdef _ResolverRegistry _resolvers
|
817 |
+
cdef _ParserContext _parser_context
|
818 |
+
cdef _ParserContext _push_parser_context
|
819 |
+
cdef int _parse_options
|
820 |
+
cdef bint _for_html
|
821 |
+
cdef bint _remove_comments
|
822 |
+
cdef bint _remove_pis
|
823 |
+
cdef bint _strip_cdata
|
824 |
+
cdef bint _collect_ids
|
825 |
+
cdef bint _resolve_external_entities
|
826 |
+
cdef XMLSchema _schema
|
827 |
+
cdef bytes _filename
|
828 |
+
cdef readonly object target
|
829 |
+
cdef object _default_encoding
|
830 |
+
cdef tuple _events_to_collect # (event_types, tag)
|
831 |
+
|
832 |
+
def __init__(self, int parse_options, bint for_html, XMLSchema schema,
|
833 |
+
remove_comments, remove_pis, strip_cdata, collect_ids,
|
834 |
+
target, encoding, bint resolve_external_entities=True):
|
835 |
+
cdef tree.xmlCharEncodingHandler* enchandler
|
836 |
+
cdef int c_encoding
|
837 |
+
if not isinstance(self, (XMLParser, HTMLParser)):
|
838 |
+
raise TypeError, "This class cannot be instantiated"
|
839 |
+
|
840 |
+
self._parse_options = parse_options
|
841 |
+
self.target = target
|
842 |
+
self._for_html = for_html
|
843 |
+
self._remove_comments = remove_comments
|
844 |
+
self._remove_pis = remove_pis
|
845 |
+
self._strip_cdata = strip_cdata
|
846 |
+
self._collect_ids = collect_ids
|
847 |
+
self._resolve_external_entities = resolve_external_entities
|
848 |
+
self._schema = schema
|
849 |
+
|
850 |
+
self._resolvers = _ResolverRegistry()
|
851 |
+
|
852 |
+
if encoding is None:
|
853 |
+
self._default_encoding = None
|
854 |
+
else:
|
855 |
+
encoding = _utf8(encoding)
|
856 |
+
enchandler = tree.xmlFindCharEncodingHandler(_cstr(encoding))
|
857 |
+
if enchandler is NULL:
|
858 |
+
raise LookupError, f"unknown encoding: '{encoding}'"
|
859 |
+
tree.xmlCharEncCloseFunc(enchandler)
|
860 |
+
self._default_encoding = encoding
|
861 |
+
|
862 |
+
cdef _setBaseURL(self, base_url):
|
863 |
+
self._filename = _encodeFilename(base_url)
|
864 |
+
|
865 |
+
cdef _collectEvents(self, event_types, tag):
|
866 |
+
if event_types is None:
|
867 |
+
event_types = ()
|
868 |
+
else:
|
869 |
+
event_types = tuple(set(event_types))
|
870 |
+
_buildParseEventFilter(event_types) # purely for validation
|
871 |
+
self._events_to_collect = (event_types, tag)
|
872 |
+
|
873 |
+
cdef _ParserContext _getParserContext(self):
|
874 |
+
cdef xmlparser.xmlParserCtxt* pctxt
|
875 |
+
if self._parser_context is None:
|
876 |
+
self._parser_context = self._createContext(self.target, None)
|
877 |
+
self._parser_context._collect_ids = self._collect_ids
|
878 |
+
if self._schema is not None:
|
879 |
+
self._parser_context._validator = \
|
880 |
+
self._schema._newSaxValidator(
|
881 |
+
self._parse_options & xmlparser.XML_PARSE_DTDATTR)
|
882 |
+
pctxt = self._newParserCtxt()
|
883 |
+
_initParserContext(self._parser_context, self._resolvers, pctxt)
|
884 |
+
self._configureSaxContext(pctxt)
|
885 |
+
return self._parser_context
|
886 |
+
|
887 |
+
cdef _ParserContext _getPushParserContext(self):
|
888 |
+
cdef xmlparser.xmlParserCtxt* pctxt
|
889 |
+
if self._push_parser_context is None:
|
890 |
+
self._push_parser_context = self._createContext(
|
891 |
+
self.target, self._events_to_collect)
|
892 |
+
self._push_parser_context._collect_ids = self._collect_ids
|
893 |
+
if self._schema is not None:
|
894 |
+
self._push_parser_context._validator = \
|
895 |
+
self._schema._newSaxValidator(
|
896 |
+
self._parse_options & xmlparser.XML_PARSE_DTDATTR)
|
897 |
+
pctxt = self._newPushParserCtxt()
|
898 |
+
_initParserContext(
|
899 |
+
self._push_parser_context, self._resolvers, pctxt)
|
900 |
+
self._configureSaxContext(pctxt)
|
901 |
+
return self._push_parser_context
|
902 |
+
|
903 |
+
cdef _ParserContext _createContext(self, target, events_to_collect):
|
904 |
+
cdef _SaxParserContext sax_context
|
905 |
+
if target is not None:
|
906 |
+
sax_context = _TargetParserContext(self)
|
907 |
+
(<_TargetParserContext>sax_context)._setTarget(target)
|
908 |
+
elif events_to_collect:
|
909 |
+
sax_context = _SaxParserContext(self)
|
910 |
+
else:
|
911 |
+
# nothing special to configure
|
912 |
+
return _ParserContext()
|
913 |
+
if events_to_collect:
|
914 |
+
events, tag = events_to_collect
|
915 |
+
sax_context._setEventFilter(events, tag)
|
916 |
+
return sax_context
|
917 |
+
|
918 |
+
@cython.final
|
919 |
+
cdef int _configureSaxContext(self, xmlparser.xmlParserCtxt* pctxt) except -1:
|
920 |
+
if self._remove_comments:
|
921 |
+
pctxt.sax.comment = NULL
|
922 |
+
if self._remove_pis:
|
923 |
+
pctxt.sax.processingInstruction = NULL
|
924 |
+
if self._strip_cdata:
|
925 |
+
# hard switch-off for CDATA nodes => makes them plain text
|
926 |
+
pctxt.sax.cdataBlock = NULL
|
927 |
+
if not self._resolve_external_entities:
|
928 |
+
pctxt.sax.getEntity = _getInternalEntityOnly
|
929 |
+
|
930 |
+
cdef int _registerHtmlErrorHandler(self, xmlparser.xmlParserCtxt* c_ctxt) except -1:
|
931 |
+
cdef xmlparser.xmlSAXHandler* sax = c_ctxt.sax
|
932 |
+
if sax is not NULL and sax.initialized and sax.initialized != xmlparser.XML_SAX2_MAGIC:
|
933 |
+
# need to extend SAX1 context to SAX2 to get proper error reports
|
934 |
+
if <xmlparser.xmlSAXHandlerV1*>sax is &htmlparser.htmlDefaultSAXHandler:
|
935 |
+
sax = <xmlparser.xmlSAXHandler*> tree.xmlMalloc(sizeof(xmlparser.xmlSAXHandler))
|
936 |
+
if sax is NULL:
|
937 |
+
raise MemoryError()
|
938 |
+
cstring_h.memcpy(sax, &htmlparser.htmlDefaultSAXHandler,
|
939 |
+
sizeof(htmlparser.htmlDefaultSAXHandler))
|
940 |
+
c_ctxt.sax = sax
|
941 |
+
sax.initialized = xmlparser.XML_SAX2_MAGIC
|
942 |
+
# Need a cast here because older libxml2 releases do not use 'const' in the functype.
|
943 |
+
sax.serror = <xmlerror.xmlStructuredErrorFunc> _receiveParserError
|
944 |
+
sax.startElementNs = NULL
|
945 |
+
sax.endElementNs = NULL
|
946 |
+
sax._private = NULL
|
947 |
+
return 0
|
948 |
+
|
949 |
+
cdef xmlparser.xmlParserCtxt* _newParserCtxt(self) except NULL:
|
950 |
+
cdef xmlparser.xmlParserCtxt* c_ctxt
|
951 |
+
if self._for_html:
|
952 |
+
c_ctxt = htmlparser.htmlCreateMemoryParserCtxt('dummy', 5)
|
953 |
+
if c_ctxt is not NULL:
|
954 |
+
self._registerHtmlErrorHandler(c_ctxt)
|
955 |
+
else:
|
956 |
+
c_ctxt = xmlparser.xmlNewParserCtxt()
|
957 |
+
if c_ctxt is NULL:
|
958 |
+
raise MemoryError
|
959 |
+
c_ctxt.sax.startDocument = _initSaxDocument
|
960 |
+
return c_ctxt
|
961 |
+
|
962 |
+
cdef xmlparser.xmlParserCtxt* _newPushParserCtxt(self) except NULL:
|
963 |
+
cdef xmlparser.xmlParserCtxt* c_ctxt
|
964 |
+
cdef char* c_filename = _cstr(self._filename) if self._filename is not None else NULL
|
965 |
+
if self._for_html:
|
966 |
+
c_ctxt = htmlparser.htmlCreatePushParserCtxt(
|
967 |
+
NULL, NULL, NULL, 0, c_filename, tree.XML_CHAR_ENCODING_NONE)
|
968 |
+
if c_ctxt is not NULL:
|
969 |
+
self._registerHtmlErrorHandler(c_ctxt)
|
970 |
+
htmlparser.htmlCtxtUseOptions(c_ctxt, self._parse_options)
|
971 |
+
else:
|
972 |
+
c_ctxt = xmlparser.xmlCreatePushParserCtxt(
|
973 |
+
NULL, NULL, NULL, 0, c_filename)
|
974 |
+
if c_ctxt is not NULL:
|
975 |
+
xmlparser.xmlCtxtUseOptions(c_ctxt, self._parse_options)
|
976 |
+
if c_ctxt is NULL:
|
977 |
+
raise MemoryError()
|
978 |
+
c_ctxt.sax.startDocument = _initSaxDocument
|
979 |
+
return c_ctxt
|
980 |
+
|
981 |
+
@property
|
982 |
+
def error_log(self):
|
983 |
+
"""The error log of the last parser run.
|
984 |
+
"""
|
985 |
+
cdef _ParserContext context
|
986 |
+
context = self._getParserContext()
|
987 |
+
return context._error_log.copy()
|
988 |
+
|
989 |
+
@property
|
990 |
+
def resolvers(self):
|
991 |
+
"""The custom resolver registry of this parser."""
|
992 |
+
return self._resolvers
|
993 |
+
|
994 |
+
@property
|
995 |
+
def version(self):
|
996 |
+
"""The version of the underlying XML parser."""
|
997 |
+
return "libxml2 %d.%d.%d" % LIBXML_VERSION
|
998 |
+
|
999 |
+
def set_element_class_lookup(self, ElementClassLookup lookup = None):
|
1000 |
+
"""set_element_class_lookup(self, lookup = None)
|
1001 |
+
|
1002 |
+
Set a lookup scheme for element classes generated from this parser.
|
1003 |
+
|
1004 |
+
Reset it by passing None or nothing.
|
1005 |
+
"""
|
1006 |
+
self._class_lookup = lookup
|
1007 |
+
|
1008 |
+
cdef _BaseParser _copy(self):
|
1009 |
+
"Create a new parser with the same configuration."
|
1010 |
+
cdef _BaseParser parser
|
1011 |
+
parser = self.__class__()
|
1012 |
+
parser._parse_options = self._parse_options
|
1013 |
+
parser._for_html = self._for_html
|
1014 |
+
parser._remove_comments = self._remove_comments
|
1015 |
+
parser._remove_pis = self._remove_pis
|
1016 |
+
parser._strip_cdata = self._strip_cdata
|
1017 |
+
parser._filename = self._filename
|
1018 |
+
parser._resolvers = self._resolvers
|
1019 |
+
parser.target = self.target
|
1020 |
+
parser._class_lookup = self._class_lookup
|
1021 |
+
parser._default_encoding = self._default_encoding
|
1022 |
+
parser._schema = self._schema
|
1023 |
+
parser._events_to_collect = self._events_to_collect
|
1024 |
+
return parser
|
1025 |
+
|
1026 |
+
def copy(self):
|
1027 |
+
"""copy(self)
|
1028 |
+
|
1029 |
+
Create a new parser with the same configuration.
|
1030 |
+
"""
|
1031 |
+
return self._copy()
|
1032 |
+
|
1033 |
+
def makeelement(self, _tag, attrib=None, nsmap=None, **_extra):
|
1034 |
+
"""makeelement(self, _tag, attrib=None, nsmap=None, **_extra)
|
1035 |
+
|
1036 |
+
Creates a new element associated with this parser.
|
1037 |
+
"""
|
1038 |
+
return _makeElement(_tag, NULL, None, self, None, None,
|
1039 |
+
attrib, nsmap, _extra)
|
1040 |
+
|
1041 |
+
# internal parser methods
|
1042 |
+
|
1043 |
+
cdef xmlDoc* _parseUnicodeDoc(self, utext, char* c_filename) except NULL:
|
1044 |
+
"""Parse unicode document, share dictionary if possible.
|
1045 |
+
"""
|
1046 |
+
cdef _ParserContext context
|
1047 |
+
cdef xmlDoc* result
|
1048 |
+
cdef xmlparser.xmlParserCtxt* pctxt
|
1049 |
+
cdef Py_ssize_t py_buffer_len
|
1050 |
+
cdef int buffer_len, c_kind
|
1051 |
+
cdef const_char* c_text
|
1052 |
+
cdef const_char* c_encoding = _PY_UNICODE_ENCODING
|
1053 |
+
if python.PyUnicode_IS_READY(utext):
|
1054 |
+
# PEP-393 string
|
1055 |
+
c_text = <const_char*>python.PyUnicode_DATA(utext)
|
1056 |
+
py_buffer_len = python.PyUnicode_GET_LENGTH(utext)
|
1057 |
+
c_kind = python.PyUnicode_KIND(utext)
|
1058 |
+
if c_kind == 1:
|
1059 |
+
if python.PyUnicode_MAX_CHAR_VALUE(utext) <= 127:
|
1060 |
+
c_encoding = 'UTF-8'
|
1061 |
+
else:
|
1062 |
+
c_encoding = 'ISO-8859-1'
|
1063 |
+
elif c_kind == 2:
|
1064 |
+
py_buffer_len *= 2
|
1065 |
+
if python.PY_BIG_ENDIAN:
|
1066 |
+
c_encoding = 'UTF-16BE' # actually UCS-2
|
1067 |
+
else:
|
1068 |
+
c_encoding = 'UTF-16LE' # actually UCS-2
|
1069 |
+
elif c_kind == 4:
|
1070 |
+
py_buffer_len *= 4
|
1071 |
+
if python.PY_BIG_ENDIAN:
|
1072 |
+
c_encoding = 'UTF-32BE' # actually UCS-4
|
1073 |
+
else:
|
1074 |
+
c_encoding = 'UTF-32LE' # actually UCS-4
|
1075 |
+
else:
|
1076 |
+
assert False, f"Illegal Unicode kind {c_kind}"
|
1077 |
+
else:
|
1078 |
+
# old Py_UNICODE string
|
1079 |
+
py_buffer_len = python.PyUnicode_GET_DATA_SIZE(utext)
|
1080 |
+
c_text = python.PyUnicode_AS_DATA(utext)
|
1081 |
+
assert 0 <= py_buffer_len <= limits.INT_MAX
|
1082 |
+
buffer_len = py_buffer_len
|
1083 |
+
|
1084 |
+
context = self._getParserContext()
|
1085 |
+
context.prepare()
|
1086 |
+
try:
|
1087 |
+
pctxt = context._c_ctxt
|
1088 |
+
__GLOBAL_PARSER_CONTEXT.initParserDict(pctxt)
|
1089 |
+
orig_options = pctxt.options
|
1090 |
+
with nogil:
|
1091 |
+
if self._for_html:
|
1092 |
+
result = htmlparser.htmlCtxtReadMemory(
|
1093 |
+
pctxt, c_text, buffer_len, c_filename, c_encoding,
|
1094 |
+
self._parse_options)
|
1095 |
+
if result is not NULL:
|
1096 |
+
if _fixHtmlDictNames(pctxt.dict, result) < 0:
|
1097 |
+
tree.xmlFreeDoc(result)
|
1098 |
+
result = NULL
|
1099 |
+
else:
|
1100 |
+
result = xmlparser.xmlCtxtReadMemory(
|
1101 |
+
pctxt, c_text, buffer_len, c_filename, c_encoding,
|
1102 |
+
self._parse_options)
|
1103 |
+
pctxt.options = orig_options # work around libxml2 problem
|
1104 |
+
|
1105 |
+
return context._handleParseResultDoc(self, result, None)
|
1106 |
+
finally:
|
1107 |
+
context.cleanup()
|
1108 |
+
|
1109 |
+
cdef xmlDoc* _parseDoc(self, char* c_text, int c_len,
|
1110 |
+
char* c_filename) except NULL:
|
1111 |
+
"""Parse document, share dictionary if possible.
|
1112 |
+
"""
|
1113 |
+
cdef _ParserContext context
|
1114 |
+
cdef xmlDoc* result
|
1115 |
+
cdef xmlparser.xmlParserCtxt* pctxt
|
1116 |
+
cdef char* c_encoding
|
1117 |
+
cdef tree.xmlCharEncoding enc
|
1118 |
+
context = self._getParserContext()
|
1119 |
+
context.prepare()
|
1120 |
+
try:
|
1121 |
+
pctxt = context._c_ctxt
|
1122 |
+
__GLOBAL_PARSER_CONTEXT.initParserDict(pctxt)
|
1123 |
+
|
1124 |
+
if self._default_encoding is None:
|
1125 |
+
c_encoding = NULL
|
1126 |
+
# libxml2 (at least 2.9.3) does not recognise UTF-32 BOMs
|
1127 |
+
# NOTE: limit to problematic cases because it changes character offsets
|
1128 |
+
if c_len >= 4 and (c_text[0] == b'\xFF' and c_text[1] == b'\xFE' and
|
1129 |
+
c_text[2] == 0 and c_text[3] == 0):
|
1130 |
+
c_encoding = "UTF-32LE"
|
1131 |
+
c_text += 4
|
1132 |
+
c_len -= 4
|
1133 |
+
elif c_len >= 4 and (c_text[0] == 0 and c_text[1] == 0 and
|
1134 |
+
c_text[2] == b'\xFE' and c_text[3] == b'\xFF'):
|
1135 |
+
c_encoding = "UTF-32BE"
|
1136 |
+
c_text += 4
|
1137 |
+
c_len -= 4
|
1138 |
+
else:
|
1139 |
+
# no BOM => try to determine encoding
|
1140 |
+
enc = tree.xmlDetectCharEncoding(<const_xmlChar*>c_text, c_len)
|
1141 |
+
if enc == tree.XML_CHAR_ENCODING_UCS4LE:
|
1142 |
+
c_encoding = 'UTF-32LE'
|
1143 |
+
elif enc == tree.XML_CHAR_ENCODING_UCS4BE:
|
1144 |
+
c_encoding = 'UTF-32BE'
|
1145 |
+
else:
|
1146 |
+
c_encoding = _cstr(self._default_encoding)
|
1147 |
+
|
1148 |
+
orig_options = pctxt.options
|
1149 |
+
with nogil:
|
1150 |
+
if self._for_html:
|
1151 |
+
result = htmlparser.htmlCtxtReadMemory(
|
1152 |
+
pctxt, c_text, c_len, c_filename,
|
1153 |
+
c_encoding, self._parse_options)
|
1154 |
+
if result is not NULL:
|
1155 |
+
if _fixHtmlDictNames(pctxt.dict, result) < 0:
|
1156 |
+
tree.xmlFreeDoc(result)
|
1157 |
+
result = NULL
|
1158 |
+
else:
|
1159 |
+
result = xmlparser.xmlCtxtReadMemory(
|
1160 |
+
pctxt, c_text, c_len, c_filename,
|
1161 |
+
c_encoding, self._parse_options)
|
1162 |
+
pctxt.options = orig_options # work around libxml2 problem
|
1163 |
+
|
1164 |
+
return context._handleParseResultDoc(self, result, None)
|
1165 |
+
finally:
|
1166 |
+
context.cleanup()
|
1167 |
+
|
1168 |
+
cdef xmlDoc* _parseDocFromFile(self, char* c_filename) except NULL:
|
1169 |
+
cdef _ParserContext context
|
1170 |
+
cdef xmlDoc* result
|
1171 |
+
cdef xmlparser.xmlParserCtxt* pctxt
|
1172 |
+
cdef char* c_encoding
|
1173 |
+
result = NULL
|
1174 |
+
|
1175 |
+
context = self._getParserContext()
|
1176 |
+
context.prepare()
|
1177 |
+
try:
|
1178 |
+
pctxt = context._c_ctxt
|
1179 |
+
__GLOBAL_PARSER_CONTEXT.initParserDict(pctxt)
|
1180 |
+
|
1181 |
+
if self._default_encoding is None:
|
1182 |
+
c_encoding = NULL
|
1183 |
+
else:
|
1184 |
+
c_encoding = _cstr(self._default_encoding)
|
1185 |
+
|
1186 |
+
orig_options = pctxt.options
|
1187 |
+
with nogil:
|
1188 |
+
if self._for_html:
|
1189 |
+
result = htmlparser.htmlCtxtReadFile(
|
1190 |
+
pctxt, c_filename, c_encoding, self._parse_options)
|
1191 |
+
if result is not NULL:
|
1192 |
+
if _fixHtmlDictNames(pctxt.dict, result) < 0:
|
1193 |
+
tree.xmlFreeDoc(result)
|
1194 |
+
result = NULL
|
1195 |
+
else:
|
1196 |
+
result = xmlparser.xmlCtxtReadFile(
|
1197 |
+
pctxt, c_filename, c_encoding, self._parse_options)
|
1198 |
+
pctxt.options = orig_options # work around libxml2 problem
|
1199 |
+
|
1200 |
+
return context._handleParseResultDoc(self, result, c_filename)
|
1201 |
+
finally:
|
1202 |
+
context.cleanup()
|
1203 |
+
|
1204 |
+
cdef xmlDoc* _parseDocFromFilelike(self, filelike, filename,
|
1205 |
+
encoding) except NULL:
|
1206 |
+
cdef _ParserContext context
|
1207 |
+
cdef _FileReaderContext file_context
|
1208 |
+
cdef xmlDoc* result
|
1209 |
+
cdef xmlparser.xmlParserCtxt* pctxt
|
1210 |
+
cdef char* c_filename
|
1211 |
+
if not filename:
|
1212 |
+
filename = None
|
1213 |
+
|
1214 |
+
context = self._getParserContext()
|
1215 |
+
context.prepare()
|
1216 |
+
try:
|
1217 |
+
pctxt = context._c_ctxt
|
1218 |
+
__GLOBAL_PARSER_CONTEXT.initParserDict(pctxt)
|
1219 |
+
file_context = _FileReaderContext(
|
1220 |
+
filelike, context, filename,
|
1221 |
+
encoding or self._default_encoding)
|
1222 |
+
result = file_context._readDoc(pctxt, self._parse_options)
|
1223 |
+
|
1224 |
+
return context._handleParseResultDoc(
|
1225 |
+
self, result, filename)
|
1226 |
+
finally:
|
1227 |
+
context.cleanup()
|
1228 |
+
|
1229 |
+
|
1230 |
+
cdef tree.xmlEntity* _getInternalEntityOnly(void* ctxt, const_xmlChar* name) noexcept nogil:
|
1231 |
+
"""
|
1232 |
+
Callback function to intercept the entity resolution when external entity loading is disabled.
|
1233 |
+
"""
|
1234 |
+
cdef tree.xmlEntity* entity = xmlparser.xmlSAX2GetEntity(ctxt, name)
|
1235 |
+
if not entity:
|
1236 |
+
return NULL
|
1237 |
+
if entity.etype not in (
|
1238 |
+
tree.xmlEntityType.XML_EXTERNAL_GENERAL_PARSED_ENTITY,
|
1239 |
+
tree.xmlEntityType.XML_EXTERNAL_GENERAL_UNPARSED_ENTITY,
|
1240 |
+
tree.xmlEntityType.XML_EXTERNAL_PARAMETER_ENTITY):
|
1241 |
+
return entity
|
1242 |
+
|
1243 |
+
# Reject all external entities and fail the parsing instead. There is currently
|
1244 |
+
# no way in libxml2 to just prevent the entity resolution in this case.
|
1245 |
+
cdef xmlerror.xmlError c_error
|
1246 |
+
cdef xmlerror.xmlStructuredErrorFunc err_func
|
1247 |
+
cdef xmlparser.xmlParserInput* parser_input
|
1248 |
+
cdef void* err_context
|
1249 |
+
|
1250 |
+
c_ctxt = <xmlparser.xmlParserCtxt *> ctxt
|
1251 |
+
err_func = xmlerror.xmlStructuredError
|
1252 |
+
if err_func:
|
1253 |
+
parser_input = c_ctxt.input
|
1254 |
+
# Copied from xmlVErrParser() in libxml2: get current input from stack.
|
1255 |
+
if parser_input and parser_input.filename is NULL and c_ctxt.inputNr > 1:
|
1256 |
+
parser_input = c_ctxt.inputTab[c_ctxt.inputNr - 2]
|
1257 |
+
|
1258 |
+
c_error = xmlerror.xmlError(
|
1259 |
+
domain=xmlerror.xmlErrorDomain.XML_FROM_PARSER,
|
1260 |
+
code=xmlerror.xmlParserErrors.XML_ERR_EXT_ENTITY_STANDALONE,
|
1261 |
+
level=xmlerror.xmlErrorLevel.XML_ERR_FATAL,
|
1262 |
+
message=b"External entity resolution is disabled for security reasons "
|
1263 |
+
b"when resolving '&%s;'. Use 'XMLParser(resolve_entities=True)' "
|
1264 |
+
b"if you consider it safe to enable it.",
|
1265 |
+
file=parser_input.filename,
|
1266 |
+
node=entity,
|
1267 |
+
str1=<char*> name,
|
1268 |
+
str2=NULL,
|
1269 |
+
str3=NULL,
|
1270 |
+
line=parser_input.line if parser_input else 0,
|
1271 |
+
int1=0,
|
1272 |
+
int2=parser_input.col if parser_input else 0,
|
1273 |
+
)
|
1274 |
+
err_context = xmlerror.xmlStructuredErrorContext
|
1275 |
+
err_func(err_context, &c_error)
|
1276 |
+
|
1277 |
+
c_ctxt.wellFormed = 0
|
1278 |
+
# The entity was looked up and does not need to be freed.
|
1279 |
+
return NULL
|
1280 |
+
|
1281 |
+
|
1282 |
+
cdef void _initSaxDocument(void* ctxt) noexcept with gil:
|
1283 |
+
xmlparser.xmlSAX2StartDocument(ctxt)
|
1284 |
+
c_ctxt = <xmlparser.xmlParserCtxt*>ctxt
|
1285 |
+
c_doc = c_ctxt.myDoc
|
1286 |
+
|
1287 |
+
# set up document dict
|
1288 |
+
if c_doc and c_ctxt.dict and not c_doc.dict:
|
1289 |
+
# I have no idea why libxml2 disables this - we need it
|
1290 |
+
c_ctxt.dictNames = 1
|
1291 |
+
c_doc.dict = c_ctxt.dict
|
1292 |
+
xmlparser.xmlDictReference(c_ctxt.dict)
|
1293 |
+
|
1294 |
+
# set up XML ID hash table
|
1295 |
+
if c_ctxt._private:
|
1296 |
+
context = <_ParserContext>c_ctxt._private
|
1297 |
+
if context._collect_ids:
|
1298 |
+
# keep the global parser dict from filling up with XML IDs
|
1299 |
+
if c_doc and not c_doc.ids:
|
1300 |
+
# memory errors are not fatal here
|
1301 |
+
c_dict = xmlparser.xmlDictCreate()
|
1302 |
+
if c_dict:
|
1303 |
+
c_doc.ids = tree.xmlHashCreateDict(0, c_dict)
|
1304 |
+
xmlparser.xmlDictFree(c_dict)
|
1305 |
+
else:
|
1306 |
+
c_doc.ids = tree.xmlHashCreate(0)
|
1307 |
+
else:
|
1308 |
+
c_ctxt.loadsubset |= xmlparser.XML_SKIP_IDS
|
1309 |
+
if c_doc and c_doc.ids and not tree.xmlHashSize(c_doc.ids):
|
1310 |
+
# already initialised but empty => clear
|
1311 |
+
tree.xmlHashFree(c_doc.ids, NULL)
|
1312 |
+
c_doc.ids = NULL
|
1313 |
+
|
1314 |
+
|
1315 |
+
############################################################
|
1316 |
+
## ET feed parser
|
1317 |
+
############################################################
|
1318 |
+
|
1319 |
+
cdef class _FeedParser(_BaseParser):
|
1320 |
+
cdef bint _feed_parser_running
|
1321 |
+
|
1322 |
+
@property
|
1323 |
+
def feed_error_log(self):
|
1324 |
+
"""The error log of the last (or current) run of the feed parser.
|
1325 |
+
|
1326 |
+
Note that this is local to the feed parser and thus is
|
1327 |
+
different from what the ``error_log`` property returns.
|
1328 |
+
"""
|
1329 |
+
return self._getPushParserContext()._error_log.copy()
|
1330 |
+
|
1331 |
+
cpdef feed(self, data):
|
1332 |
+
"""feed(self, data)
|
1333 |
+
|
1334 |
+
Feeds data to the parser. The argument should be an 8-bit string
|
1335 |
+
buffer containing encoded data, although Unicode is supported as long
|
1336 |
+
as both string types are not mixed.
|
1337 |
+
|
1338 |
+
This is the main entry point to the consumer interface of a
|
1339 |
+
parser. The parser will parse as much of the XML stream as it
|
1340 |
+
can on each call. To finish parsing or to reset the parser,
|
1341 |
+
call the ``close()`` method. Both methods may raise
|
1342 |
+
ParseError if errors occur in the input data. If an error is
|
1343 |
+
raised, there is no longer a need to call ``close()``.
|
1344 |
+
|
1345 |
+
The feed parser interface is independent of the normal parser
|
1346 |
+
usage. You can use the same parser as a feed parser and in
|
1347 |
+
the ``parse()`` function concurrently.
|
1348 |
+
"""
|
1349 |
+
cdef _ParserContext context
|
1350 |
+
cdef bytes bstring
|
1351 |
+
cdef xmlparser.xmlParserCtxt* pctxt
|
1352 |
+
cdef Py_ssize_t py_buffer_len, ustart
|
1353 |
+
cdef const_char* char_data
|
1354 |
+
cdef const_char* c_encoding
|
1355 |
+
cdef int buffer_len
|
1356 |
+
cdef int error
|
1357 |
+
cdef bint recover = self._parse_options & xmlparser.XML_PARSE_RECOVER
|
1358 |
+
|
1359 |
+
if isinstance(data, bytes):
|
1360 |
+
if self._default_encoding is None:
|
1361 |
+
c_encoding = NULL
|
1362 |
+
else:
|
1363 |
+
c_encoding = self._default_encoding
|
1364 |
+
char_data = _cstr(data)
|
1365 |
+
py_buffer_len = python.PyBytes_GET_SIZE(data)
|
1366 |
+
ustart = 0
|
1367 |
+
elif isinstance(data, unicode):
|
1368 |
+
c_encoding = b"UTF-8"
|
1369 |
+
char_data = NULL
|
1370 |
+
py_buffer_len = len(<unicode> data)
|
1371 |
+
ustart = 0
|
1372 |
+
else:
|
1373 |
+
raise TypeError, "Parsing requires string data"
|
1374 |
+
|
1375 |
+
context = self._getPushParserContext()
|
1376 |
+
pctxt = context._c_ctxt
|
1377 |
+
error = 0
|
1378 |
+
if not self._feed_parser_running:
|
1379 |
+
context.prepare(set_document_loader=False)
|
1380 |
+
self._feed_parser_running = 1
|
1381 |
+
c_filename = (_cstr(self._filename)
|
1382 |
+
if self._filename is not None else NULL)
|
1383 |
+
|
1384 |
+
# We have to give *mlCtxtResetPush() enough input to figure
|
1385 |
+
# out the character encoding (at least four bytes),
|
1386 |
+
# however if we give it all we got, we'll have nothing for
|
1387 |
+
# *mlParseChunk() and things go wrong.
|
1388 |
+
buffer_len = 0
|
1389 |
+
if char_data is not NULL:
|
1390 |
+
buffer_len = 4 if py_buffer_len > 4 else <int>py_buffer_len
|
1391 |
+
orig_loader = _register_document_loader()
|
1392 |
+
if self._for_html:
|
1393 |
+
error = _htmlCtxtResetPush(
|
1394 |
+
pctxt, char_data, buffer_len, c_filename, c_encoding,
|
1395 |
+
self._parse_options)
|
1396 |
+
else:
|
1397 |
+
xmlparser.xmlCtxtUseOptions(pctxt, self._parse_options)
|
1398 |
+
error = xmlparser.xmlCtxtResetPush(
|
1399 |
+
pctxt, char_data, buffer_len, c_filename, c_encoding)
|
1400 |
+
_reset_document_loader(orig_loader)
|
1401 |
+
py_buffer_len -= buffer_len
|
1402 |
+
char_data += buffer_len
|
1403 |
+
if error:
|
1404 |
+
raise MemoryError()
|
1405 |
+
__GLOBAL_PARSER_CONTEXT.initParserDict(pctxt)
|
1406 |
+
|
1407 |
+
#print pctxt.charset, 'NONE' if c_encoding is NULL else c_encoding
|
1408 |
+
|
1409 |
+
fixup_error = 0
|
1410 |
+
while py_buffer_len > 0 and (error == 0 or recover):
|
1411 |
+
if char_data is NULL:
|
1412 |
+
# Unicode parsing by converting chunks to UTF-8
|
1413 |
+
buffer_len = 2**19 # len(bytes) <= 4 * (2**19) == 2 MiB
|
1414 |
+
bstring = (<unicode> data)[ustart : ustart+buffer_len].encode('UTF-8')
|
1415 |
+
ustart += buffer_len
|
1416 |
+
py_buffer_len -= buffer_len # may end up < 0
|
1417 |
+
error, fixup_error = _parse_data_chunk(pctxt, <const char*> bstring, <int> len(bstring))
|
1418 |
+
else:
|
1419 |
+
# Direct byte string parsing.
|
1420 |
+
buffer_len = <int>py_buffer_len if py_buffer_len <= limits.INT_MAX else limits.INT_MAX
|
1421 |
+
error, fixup_error = _parse_data_chunk(pctxt, char_data, buffer_len)
|
1422 |
+
py_buffer_len -= buffer_len
|
1423 |
+
char_data += buffer_len
|
1424 |
+
|
1425 |
+
if fixup_error:
|
1426 |
+
context.store_exception(MemoryError())
|
1427 |
+
|
1428 |
+
if context._has_raised():
|
1429 |
+
# propagate Python exceptions immediately
|
1430 |
+
recover = 0
|
1431 |
+
error = 1
|
1432 |
+
break
|
1433 |
+
|
1434 |
+
if error and not pctxt.replaceEntities and not pctxt.validate:
|
1435 |
+
# in this mode, we ignore errors about undefined entities
|
1436 |
+
for entry in context._error_log.filter_from_errors():
|
1437 |
+
if entry.type != ErrorTypes.WAR_UNDECLARED_ENTITY and \
|
1438 |
+
entry.type != ErrorTypes.ERR_UNDECLARED_ENTITY:
|
1439 |
+
break
|
1440 |
+
else:
|
1441 |
+
error = 0
|
1442 |
+
|
1443 |
+
if not pctxt.wellFormed and pctxt.disableSAX and context._has_raised():
|
1444 |
+
# propagate Python exceptions immediately
|
1445 |
+
recover = 0
|
1446 |
+
error = 1
|
1447 |
+
|
1448 |
+
if fixup_error or not recover and (error or not pctxt.wellFormed):
|
1449 |
+
self._feed_parser_running = 0
|
1450 |
+
try:
|
1451 |
+
context._handleParseResult(self, pctxt.myDoc, None)
|
1452 |
+
finally:
|
1453 |
+
context.cleanup()
|
1454 |
+
|
1455 |
+
cpdef close(self):
|
1456 |
+
"""close(self)
|
1457 |
+
|
1458 |
+
Terminates feeding data to this parser. This tells the parser to
|
1459 |
+
process any remaining data in the feed buffer, and then returns the
|
1460 |
+
root Element of the tree that was parsed.
|
1461 |
+
|
1462 |
+
This method must be called after passing the last chunk of data into
|
1463 |
+
the ``feed()`` method. It should only be called when using the feed
|
1464 |
+
parser interface, all other usage is undefined.
|
1465 |
+
"""
|
1466 |
+
if not self._feed_parser_running:
|
1467 |
+
raise XMLSyntaxError("no element found",
|
1468 |
+
xmlerror.XML_ERR_INTERNAL_ERROR, 0, 0,
|
1469 |
+
self._filename)
|
1470 |
+
|
1471 |
+
context = self._getPushParserContext()
|
1472 |
+
pctxt = context._c_ctxt
|
1473 |
+
|
1474 |
+
self._feed_parser_running = 0
|
1475 |
+
if self._for_html:
|
1476 |
+
htmlparser.htmlParseChunk(pctxt, NULL, 0, 1)
|
1477 |
+
else:
|
1478 |
+
xmlparser.xmlParseChunk(pctxt, NULL, 0, 1)
|
1479 |
+
|
1480 |
+
if (pctxt.recovery and not pctxt.disableSAX and
|
1481 |
+
isinstance(context, _SaxParserContext)):
|
1482 |
+
# apply any left-over 'end' events
|
1483 |
+
(<_SaxParserContext>context).flushEvents()
|
1484 |
+
|
1485 |
+
try:
|
1486 |
+
result = context._handleParseResult(self, pctxt.myDoc, None)
|
1487 |
+
finally:
|
1488 |
+
context.cleanup()
|
1489 |
+
|
1490 |
+
if isinstance(result, _Document):
|
1491 |
+
return (<_Document>result).getroot()
|
1492 |
+
else:
|
1493 |
+
return result
|
1494 |
+
|
1495 |
+
|
1496 |
+
cdef (int, int) _parse_data_chunk(xmlparser.xmlParserCtxt* c_ctxt,
|
1497 |
+
const char* char_data, int buffer_len):
|
1498 |
+
fixup_error = 0
|
1499 |
+
with nogil:
|
1500 |
+
if c_ctxt.html:
|
1501 |
+
c_node = c_ctxt.node # last node where the parser stopped
|
1502 |
+
orig_loader = _register_document_loader()
|
1503 |
+
error = htmlparser.htmlParseChunk(c_ctxt, char_data, buffer_len, 0)
|
1504 |
+
_reset_document_loader(orig_loader)
|
1505 |
+
# and now for the fun part: move node names to the dict
|
1506 |
+
if c_ctxt.myDoc:
|
1507 |
+
fixup_error = _fixHtmlDictSubtreeNames(
|
1508 |
+
c_ctxt.dict, c_ctxt.myDoc, c_node)
|
1509 |
+
if c_ctxt.myDoc.dict and c_ctxt.myDoc.dict is not c_ctxt.dict:
|
1510 |
+
xmlparser.xmlDictFree(c_ctxt.myDoc.dict)
|
1511 |
+
c_ctxt.myDoc.dict = c_ctxt.dict
|
1512 |
+
xmlparser.xmlDictReference(c_ctxt.dict)
|
1513 |
+
else:
|
1514 |
+
orig_loader = _register_document_loader()
|
1515 |
+
error = xmlparser.xmlParseChunk(c_ctxt, char_data, buffer_len, 0)
|
1516 |
+
_reset_document_loader(orig_loader)
|
1517 |
+
return (error, fixup_error)
|
1518 |
+
|
1519 |
+
|
1520 |
+
cdef int _htmlCtxtResetPush(xmlparser.xmlParserCtxt* c_ctxt,
|
1521 |
+
const_char* c_data, int buffer_len,
|
1522 |
+
const_char* c_filename, const_char* c_encoding,
|
1523 |
+
int parse_options) except -1:
|
1524 |
+
cdef xmlparser.xmlParserInput* c_input_stream
|
1525 |
+
# libxml2 lacks an HTML push parser setup function
|
1526 |
+
error = xmlparser.xmlCtxtResetPush(
|
1527 |
+
c_ctxt, c_data, buffer_len, c_filename, c_encoding)
|
1528 |
+
if error:
|
1529 |
+
return error
|
1530 |
+
|
1531 |
+
# fix libxml2 setup for HTML
|
1532 |
+
c_ctxt.progressive = 1
|
1533 |
+
c_ctxt.html = 1
|
1534 |
+
htmlparser.htmlCtxtUseOptions(c_ctxt, parse_options)
|
1535 |
+
|
1536 |
+
return 0
|
1537 |
+
|
1538 |
+
|
1539 |
+
############################################################
|
1540 |
+
## XML parser
|
1541 |
+
############################################################
|
1542 |
+
|
1543 |
+
cdef int _XML_DEFAULT_PARSE_OPTIONS
|
1544 |
+
_XML_DEFAULT_PARSE_OPTIONS = (
|
1545 |
+
xmlparser.XML_PARSE_NOENT |
|
1546 |
+
xmlparser.XML_PARSE_NOCDATA |
|
1547 |
+
xmlparser.XML_PARSE_NONET |
|
1548 |
+
xmlparser.XML_PARSE_COMPACT |
|
1549 |
+
xmlparser.XML_PARSE_BIG_LINES
|
1550 |
+
)
|
1551 |
+
|
1552 |
+
cdef class XMLParser(_FeedParser):
|
1553 |
+
"""XMLParser(self, encoding=None, attribute_defaults=False, dtd_validation=False, load_dtd=False, no_network=True, ns_clean=False, recover=False, schema: XMLSchema =None, huge_tree=False, remove_blank_text=False, resolve_entities=True, remove_comments=False, remove_pis=False, strip_cdata=True, collect_ids=True, target=None, compact=True)
|
1554 |
+
|
1555 |
+
The XML parser.
|
1556 |
+
|
1557 |
+
Parsers can be supplied as additional argument to various parse
|
1558 |
+
functions of the lxml API. A default parser is always available
|
1559 |
+
and can be replaced by a call to the global function
|
1560 |
+
'set_default_parser'. New parsers can be created at any time
|
1561 |
+
without a major run-time overhead.
|
1562 |
+
|
1563 |
+
The keyword arguments in the constructor are mainly based on the
|
1564 |
+
libxml2 parser configuration. A DTD will also be loaded if DTD
|
1565 |
+
validation or attribute default values are requested (unless you
|
1566 |
+
additionally provide an XMLSchema from which the default
|
1567 |
+
attributes can be read).
|
1568 |
+
|
1569 |
+
Available boolean keyword arguments:
|
1570 |
+
|
1571 |
+
- attribute_defaults - inject default attributes from DTD or XMLSchema
|
1572 |
+
- dtd_validation - validate against a DTD referenced by the document
|
1573 |
+
- load_dtd - use DTD for parsing
|
1574 |
+
- no_network - prevent network access for related files (default: True)
|
1575 |
+
- ns_clean - clean up redundant namespace declarations
|
1576 |
+
- recover - try hard to parse through broken XML
|
1577 |
+
- remove_blank_text - discard blank text nodes that appear ignorable
|
1578 |
+
- remove_comments - discard comments
|
1579 |
+
- remove_pis - discard processing instructions
|
1580 |
+
- strip_cdata - replace CDATA sections by normal text content (default: True)
|
1581 |
+
- compact - save memory for short text content (default: True)
|
1582 |
+
- collect_ids - use a hash table of XML IDs for fast access (default: True, always True with DTD validation)
|
1583 |
+
- huge_tree - disable security restrictions and support very deep trees
|
1584 |
+
and very long text content (only affects libxml2 2.7+)
|
1585 |
+
|
1586 |
+
Other keyword arguments:
|
1587 |
+
|
1588 |
+
- resolve_entities - replace entities by their text value: False for keeping the
|
1589 |
+
entity references, True for resolving them, and 'internal' for resolving
|
1590 |
+
internal definitions only (no external file/URL access).
|
1591 |
+
The default used to be True and was changed to 'internal' in lxml 5.0.
|
1592 |
+
- encoding - override the document encoding (note: libiconv encoding name)
|
1593 |
+
- target - a parser target object that will receive the parse events
|
1594 |
+
- schema - an XMLSchema to validate against
|
1595 |
+
|
1596 |
+
Note that you should avoid sharing parsers between threads. While this is
|
1597 |
+
not harmful, it is more efficient to use separate parsers. This does not
|
1598 |
+
apply to the default parser.
|
1599 |
+
"""
|
1600 |
+
def __init__(self, *, encoding=None, attribute_defaults=False,
|
1601 |
+
dtd_validation=False, load_dtd=False, no_network=True,
|
1602 |
+
ns_clean=False, recover=False, XMLSchema schema=None,
|
1603 |
+
huge_tree=False, remove_blank_text=False, resolve_entities='internal',
|
1604 |
+
remove_comments=False, remove_pis=False, strip_cdata=True,
|
1605 |
+
collect_ids=True, target=None, compact=True):
|
1606 |
+
cdef int parse_options
|
1607 |
+
cdef bint resolve_external = True
|
1608 |
+
parse_options = _XML_DEFAULT_PARSE_OPTIONS
|
1609 |
+
if load_dtd:
|
1610 |
+
parse_options = parse_options | xmlparser.XML_PARSE_DTDLOAD
|
1611 |
+
if dtd_validation:
|
1612 |
+
parse_options = parse_options | xmlparser.XML_PARSE_DTDVALID | \
|
1613 |
+
xmlparser.XML_PARSE_DTDLOAD
|
1614 |
+
if attribute_defaults:
|
1615 |
+
parse_options = parse_options | xmlparser.XML_PARSE_DTDATTR
|
1616 |
+
if schema is None:
|
1617 |
+
parse_options = parse_options | xmlparser.XML_PARSE_DTDLOAD
|
1618 |
+
if ns_clean:
|
1619 |
+
parse_options = parse_options | xmlparser.XML_PARSE_NSCLEAN
|
1620 |
+
if recover:
|
1621 |
+
parse_options = parse_options | xmlparser.XML_PARSE_RECOVER
|
1622 |
+
if remove_blank_text:
|
1623 |
+
parse_options = parse_options | xmlparser.XML_PARSE_NOBLANKS
|
1624 |
+
if huge_tree:
|
1625 |
+
parse_options = parse_options | xmlparser.XML_PARSE_HUGE
|
1626 |
+
if not no_network:
|
1627 |
+
parse_options = parse_options ^ xmlparser.XML_PARSE_NONET
|
1628 |
+
if not compact:
|
1629 |
+
parse_options = parse_options ^ xmlparser.XML_PARSE_COMPACT
|
1630 |
+
if not resolve_entities:
|
1631 |
+
parse_options = parse_options ^ xmlparser.XML_PARSE_NOENT
|
1632 |
+
elif resolve_entities == 'internal':
|
1633 |
+
resolve_external = False
|
1634 |
+
if not strip_cdata:
|
1635 |
+
parse_options = parse_options ^ xmlparser.XML_PARSE_NOCDATA
|
1636 |
+
|
1637 |
+
_BaseParser.__init__(self, parse_options, False, schema,
|
1638 |
+
remove_comments, remove_pis, strip_cdata,
|
1639 |
+
collect_ids, target, encoding, resolve_external)
|
1640 |
+
|
1641 |
+
|
1642 |
+
cdef class XMLPullParser(XMLParser):
|
1643 |
+
"""XMLPullParser(self, events=None, *, tag=None, **kwargs)
|
1644 |
+
|
1645 |
+
XML parser that collects parse events in an iterator.
|
1646 |
+
|
1647 |
+
The collected events are the same as for iterparse(), but the
|
1648 |
+
parser itself is non-blocking in the sense that it receives
|
1649 |
+
data chunks incrementally through its .feed() method, instead
|
1650 |
+
of reading them directly from a file(-like) object all by itself.
|
1651 |
+
|
1652 |
+
By default, it collects Element end events. To change that,
|
1653 |
+
pass any subset of the available events into the ``events``
|
1654 |
+
argument: ``'start'``, ``'end'``, ``'start-ns'``,
|
1655 |
+
``'end-ns'``, ``'comment'``, ``'pi'``.
|
1656 |
+
|
1657 |
+
To support loading external dependencies relative to the input
|
1658 |
+
source, you can pass the ``base_url``.
|
1659 |
+
"""
|
1660 |
+
def __init__(self, events=None, *, tag=None, base_url=None, **kwargs):
|
1661 |
+
XMLParser.__init__(self, **kwargs)
|
1662 |
+
if events is None:
|
1663 |
+
events = ('end',)
|
1664 |
+
self._setBaseURL(base_url)
|
1665 |
+
self._collectEvents(events, tag)
|
1666 |
+
|
1667 |
+
def read_events(self):
|
1668 |
+
return (<_SaxParserContext?>self._getPushParserContext()).events_iterator
|
1669 |
+
|
1670 |
+
|
1671 |
+
cdef class ETCompatXMLParser(XMLParser):
|
1672 |
+
"""ETCompatXMLParser(self, encoding=None, attribute_defaults=False, \
|
1673 |
+
dtd_validation=False, load_dtd=False, no_network=True, \
|
1674 |
+
ns_clean=False, recover=False, schema=None, \
|
1675 |
+
huge_tree=False, remove_blank_text=False, resolve_entities=True, \
|
1676 |
+
remove_comments=True, remove_pis=True, strip_cdata=True, \
|
1677 |
+
target=None, compact=True)
|
1678 |
+
|
1679 |
+
An XML parser with an ElementTree compatible default setup.
|
1680 |
+
|
1681 |
+
See the XMLParser class for details.
|
1682 |
+
|
1683 |
+
This parser has ``remove_comments`` and ``remove_pis`` enabled by default
|
1684 |
+
and thus ignores comments and processing instructions.
|
1685 |
+
"""
|
1686 |
+
def __init__(self, *, encoding=None, attribute_defaults=False,
|
1687 |
+
dtd_validation=False, load_dtd=False, no_network=True,
|
1688 |
+
ns_clean=False, recover=False, schema=None,
|
1689 |
+
huge_tree=False, remove_blank_text=False, resolve_entities=True,
|
1690 |
+
remove_comments=True, remove_pis=True, strip_cdata=True,
|
1691 |
+
target=None, compact=True):
|
1692 |
+
XMLParser.__init__(self,
|
1693 |
+
attribute_defaults=attribute_defaults,
|
1694 |
+
dtd_validation=dtd_validation,
|
1695 |
+
load_dtd=load_dtd,
|
1696 |
+
no_network=no_network,
|
1697 |
+
ns_clean=ns_clean,
|
1698 |
+
recover=recover,
|
1699 |
+
remove_blank_text=remove_blank_text,
|
1700 |
+
huge_tree=huge_tree,
|
1701 |
+
compact=compact,
|
1702 |
+
resolve_entities=resolve_entities,
|
1703 |
+
remove_comments=remove_comments,
|
1704 |
+
remove_pis=remove_pis,
|
1705 |
+
strip_cdata=strip_cdata,
|
1706 |
+
target=target,
|
1707 |
+
encoding=encoding,
|
1708 |
+
schema=schema)
|
1709 |
+
|
1710 |
+
# ET 1.2 compatible name
|
1711 |
+
XMLTreeBuilder = ETCompatXMLParser
|
1712 |
+
|
1713 |
+
|
1714 |
+
cdef XMLParser __DEFAULT_XML_PARSER
|
1715 |
+
__DEFAULT_XML_PARSER = XMLParser()
|
1716 |
+
|
1717 |
+
__GLOBAL_PARSER_CONTEXT.setDefaultParser(__DEFAULT_XML_PARSER)
|
1718 |
+
|
1719 |
+
def set_default_parser(_BaseParser parser=None):
|
1720 |
+
"""set_default_parser(parser=None)
|
1721 |
+
|
1722 |
+
Set a default parser for the current thread. This parser is used
|
1723 |
+
globally whenever no parser is supplied to the various parse functions of
|
1724 |
+
the lxml API. If this function is called without a parser (or if it is
|
1725 |
+
None), the default parser is reset to the original configuration.
|
1726 |
+
|
1727 |
+
Note that the pre-installed default parser is not thread-safe. Avoid the
|
1728 |
+
default parser in multi-threaded environments. You can create a separate
|
1729 |
+
parser for each thread explicitly or use a parser pool.
|
1730 |
+
"""
|
1731 |
+
if parser is None:
|
1732 |
+
parser = __DEFAULT_XML_PARSER
|
1733 |
+
__GLOBAL_PARSER_CONTEXT.setDefaultParser(parser)
|
1734 |
+
|
1735 |
+
def get_default_parser():
|
1736 |
+
"get_default_parser()"
|
1737 |
+
return __GLOBAL_PARSER_CONTEXT.getDefaultParser()
|
1738 |
+
|
1739 |
+
############################################################
|
1740 |
+
## HTML parser
|
1741 |
+
############################################################
|
1742 |
+
|
1743 |
+
cdef int _HTML_DEFAULT_PARSE_OPTIONS
|
1744 |
+
_HTML_DEFAULT_PARSE_OPTIONS = (
|
1745 |
+
htmlparser.HTML_PARSE_RECOVER |
|
1746 |
+
htmlparser.HTML_PARSE_NONET |
|
1747 |
+
htmlparser.HTML_PARSE_COMPACT
|
1748 |
+
)
|
1749 |
+
|
1750 |
+
cdef class HTMLParser(_FeedParser):
|
1751 |
+
"""HTMLParser(self, encoding=None, remove_blank_text=False, \
|
1752 |
+
remove_comments=False, remove_pis=False, strip_cdata=True, \
|
1753 |
+
no_network=True, target=None, schema: XMLSchema =None, \
|
1754 |
+
recover=True, compact=True, collect_ids=True, huge_tree=False)
|
1755 |
+
|
1756 |
+
The HTML parser.
|
1757 |
+
|
1758 |
+
This parser allows reading HTML into a normal XML tree. By
|
1759 |
+
default, it can read broken (non well-formed) HTML, depending on
|
1760 |
+
the capabilities of libxml2. Use the 'recover' option to switch
|
1761 |
+
this off.
|
1762 |
+
|
1763 |
+
Available boolean keyword arguments:
|
1764 |
+
|
1765 |
+
- recover - try hard to parse through broken HTML (default: True)
|
1766 |
+
- no_network - prevent network access for related files (default: True)
|
1767 |
+
- remove_blank_text - discard empty text nodes that are ignorable (i.e. not actual text content)
|
1768 |
+
- remove_comments - discard comments
|
1769 |
+
- remove_pis - discard processing instructions
|
1770 |
+
- strip_cdata - replace CDATA sections by normal text content (default: True)
|
1771 |
+
- compact - save memory for short text content (default: True)
|
1772 |
+
- default_doctype - add a default doctype even if it is not found in the HTML (default: True)
|
1773 |
+
- collect_ids - use a hash table of XML IDs for fast access (default: True)
|
1774 |
+
- huge_tree - disable security restrictions and support very deep trees
|
1775 |
+
and very long text content (only affects libxml2 2.7+)
|
1776 |
+
|
1777 |
+
Other keyword arguments:
|
1778 |
+
|
1779 |
+
- encoding - override the document encoding (note: libiconv encoding name)
|
1780 |
+
- target - a parser target object that will receive the parse events
|
1781 |
+
- schema - an XMLSchema to validate against
|
1782 |
+
|
1783 |
+
Note that you should avoid sharing parsers between threads for performance
|
1784 |
+
reasons.
|
1785 |
+
"""
|
1786 |
+
def __init__(self, *, encoding=None, remove_blank_text=False,
|
1787 |
+
remove_comments=False, remove_pis=False, strip_cdata=True,
|
1788 |
+
no_network=True, target=None, XMLSchema schema=None,
|
1789 |
+
recover=True, compact=True, default_doctype=True,
|
1790 |
+
collect_ids=True, huge_tree=False):
|
1791 |
+
cdef int parse_options
|
1792 |
+
parse_options = _HTML_DEFAULT_PARSE_OPTIONS
|
1793 |
+
if remove_blank_text:
|
1794 |
+
parse_options = parse_options | htmlparser.HTML_PARSE_NOBLANKS
|
1795 |
+
if not recover:
|
1796 |
+
parse_options = parse_options ^ htmlparser.HTML_PARSE_RECOVER
|
1797 |
+
if not no_network:
|
1798 |
+
parse_options = parse_options ^ htmlparser.HTML_PARSE_NONET
|
1799 |
+
if not compact:
|
1800 |
+
parse_options = parse_options ^ htmlparser.HTML_PARSE_COMPACT
|
1801 |
+
if not default_doctype:
|
1802 |
+
parse_options = parse_options ^ htmlparser.HTML_PARSE_NODEFDTD
|
1803 |
+
if huge_tree:
|
1804 |
+
parse_options = parse_options | xmlparser.XML_PARSE_HUGE
|
1805 |
+
|
1806 |
+
_BaseParser.__init__(self, parse_options, True, schema,
|
1807 |
+
remove_comments, remove_pis, strip_cdata,
|
1808 |
+
collect_ids, target, encoding)
|
1809 |
+
|
1810 |
+
|
1811 |
+
cdef HTMLParser __DEFAULT_HTML_PARSER
|
1812 |
+
__DEFAULT_HTML_PARSER = HTMLParser()
|
1813 |
+
|
1814 |
+
|
1815 |
+
cdef class HTMLPullParser(HTMLParser):
|
1816 |
+
"""HTMLPullParser(self, events=None, *, tag=None, base_url=None, **kwargs)
|
1817 |
+
|
1818 |
+
HTML parser that collects parse events in an iterator.
|
1819 |
+
|
1820 |
+
The collected events are the same as for iterparse(), but the
|
1821 |
+
parser itself is non-blocking in the sense that it receives
|
1822 |
+
data chunks incrementally through its .feed() method, instead
|
1823 |
+
of reading them directly from a file(-like) object all by itself.
|
1824 |
+
|
1825 |
+
By default, it collects Element end events. To change that,
|
1826 |
+
pass any subset of the available events into the ``events``
|
1827 |
+
argument: ``'start'``, ``'end'``, ``'start-ns'``,
|
1828 |
+
``'end-ns'``, ``'comment'``, ``'pi'``.
|
1829 |
+
|
1830 |
+
To support loading external dependencies relative to the input
|
1831 |
+
source, you can pass the ``base_url``.
|
1832 |
+
"""
|
1833 |
+
def __init__(self, events=None, *, tag=None, base_url=None, **kwargs):
|
1834 |
+
HTMLParser.__init__(self, **kwargs)
|
1835 |
+
if events is None:
|
1836 |
+
events = ('end',)
|
1837 |
+
self._setBaseURL(base_url)
|
1838 |
+
self._collectEvents(events, tag)
|
1839 |
+
|
1840 |
+
def read_events(self):
|
1841 |
+
return (<_SaxParserContext?>self._getPushParserContext()).events_iterator
|
1842 |
+
|
1843 |
+
|
1844 |
+
############################################################
|
1845 |
+
## helper functions for document creation
|
1846 |
+
############################################################
|
1847 |
+
|
1848 |
+
cdef xmlDoc* _parseDoc(text, filename, _BaseParser parser) except NULL:
|
1849 |
+
cdef char* c_filename
|
1850 |
+
cdef char* c_text
|
1851 |
+
cdef Py_ssize_t c_len
|
1852 |
+
if parser is None:
|
1853 |
+
parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
|
1854 |
+
if not filename:
|
1855 |
+
c_filename = NULL
|
1856 |
+
else:
|
1857 |
+
filename_utf = _encodeFilenameUTF8(filename)
|
1858 |
+
c_filename = _cstr(filename_utf)
|
1859 |
+
if isinstance(text, unicode):
|
1860 |
+
if python.PyUnicode_IS_READY(text):
|
1861 |
+
# PEP-393 Unicode string
|
1862 |
+
c_len = python.PyUnicode_GET_LENGTH(text) * python.PyUnicode_KIND(text)
|
1863 |
+
else:
|
1864 |
+
# old Py_UNICODE string
|
1865 |
+
c_len = python.PyUnicode_GET_DATA_SIZE(text)
|
1866 |
+
if c_len > limits.INT_MAX:
|
1867 |
+
return (<_BaseParser>parser)._parseDocFromFilelike(
|
1868 |
+
StringIO(text), filename, None)
|
1869 |
+
return (<_BaseParser>parser)._parseUnicodeDoc(text, c_filename)
|
1870 |
+
else:
|
1871 |
+
c_len = python.PyBytes_GET_SIZE(text)
|
1872 |
+
if c_len > limits.INT_MAX:
|
1873 |
+
return (<_BaseParser>parser)._parseDocFromFilelike(
|
1874 |
+
BytesIO(text), filename, None)
|
1875 |
+
c_text = _cstr(text)
|
1876 |
+
return (<_BaseParser>parser)._parseDoc(c_text, c_len, c_filename)
|
1877 |
+
|
1878 |
+
cdef xmlDoc* _parseDocFromFile(filename8, _BaseParser parser) except NULL:
|
1879 |
+
if parser is None:
|
1880 |
+
parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
|
1881 |
+
return (<_BaseParser>parser)._parseDocFromFile(_cstr(filename8))
|
1882 |
+
|
1883 |
+
cdef xmlDoc* _parseDocFromFilelike(source, filename,
|
1884 |
+
_BaseParser parser) except NULL:
|
1885 |
+
if parser is None:
|
1886 |
+
parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
|
1887 |
+
return (<_BaseParser>parser)._parseDocFromFilelike(source, filename, None)
|
1888 |
+
|
1889 |
+
cdef xmlDoc* _newXMLDoc() except NULL:
|
1890 |
+
cdef xmlDoc* result
|
1891 |
+
result = tree.xmlNewDoc(NULL)
|
1892 |
+
if result is NULL:
|
1893 |
+
raise MemoryError()
|
1894 |
+
if result.encoding is NULL:
|
1895 |
+
result.encoding = tree.xmlStrdup(<unsigned char*>"UTF-8")
|
1896 |
+
__GLOBAL_PARSER_CONTEXT.initDocDict(result)
|
1897 |
+
return result
|
1898 |
+
|
1899 |
+
cdef xmlDoc* _newHTMLDoc() except NULL:
|
1900 |
+
cdef xmlDoc* result
|
1901 |
+
result = tree.htmlNewDoc(NULL, NULL)
|
1902 |
+
if result is NULL:
|
1903 |
+
raise MemoryError()
|
1904 |
+
__GLOBAL_PARSER_CONTEXT.initDocDict(result)
|
1905 |
+
return result
|
1906 |
+
|
1907 |
+
cdef xmlDoc* _copyDoc(xmlDoc* c_doc, int recursive) except NULL:
|
1908 |
+
cdef xmlDoc* result
|
1909 |
+
if recursive:
|
1910 |
+
with nogil:
|
1911 |
+
result = tree.xmlCopyDoc(c_doc, recursive)
|
1912 |
+
else:
|
1913 |
+
result = tree.xmlCopyDoc(c_doc, 0)
|
1914 |
+
if result is NULL:
|
1915 |
+
raise MemoryError()
|
1916 |
+
__GLOBAL_PARSER_CONTEXT.initDocDict(result)
|
1917 |
+
return result
|
1918 |
+
|
1919 |
+
cdef xmlDoc* _copyDocRoot(xmlDoc* c_doc, xmlNode* c_new_root) except NULL:
|
1920 |
+
"Recursively copy the document and make c_new_root the new root node."
|
1921 |
+
cdef xmlDoc* result
|
1922 |
+
cdef xmlNode* c_node
|
1923 |
+
result = tree.xmlCopyDoc(c_doc, 0) # non recursive
|
1924 |
+
__GLOBAL_PARSER_CONTEXT.initDocDict(result)
|
1925 |
+
with nogil:
|
1926 |
+
c_node = tree.xmlDocCopyNode(c_new_root, result, 1) # recursive
|
1927 |
+
if c_node is NULL:
|
1928 |
+
raise MemoryError()
|
1929 |
+
tree.xmlDocSetRootElement(result, c_node)
|
1930 |
+
_copyTail(c_new_root.next, c_node)
|
1931 |
+
return result
|
1932 |
+
|
1933 |
+
cdef xmlNode* _copyNodeToDoc(xmlNode* c_node, xmlDoc* c_doc) except NULL:
|
1934 |
+
"Recursively copy the element into the document. c_doc is not modified."
|
1935 |
+
cdef xmlNode* c_root
|
1936 |
+
c_root = tree.xmlDocCopyNode(c_node, c_doc, 1) # recursive
|
1937 |
+
if c_root is NULL:
|
1938 |
+
raise MemoryError()
|
1939 |
+
_copyTail(c_node.next, c_root)
|
1940 |
+
return c_root
|
1941 |
+
|
1942 |
+
|
1943 |
+
############################################################
|
1944 |
+
## API level helper functions for _Document creation
|
1945 |
+
############################################################
|
1946 |
+
|
1947 |
+
cdef _Document _parseDocument(source, _BaseParser parser, base_url):
|
1948 |
+
cdef _Document doc
|
1949 |
+
source = _getFSPathOrObject(source)
|
1950 |
+
if _isString(source):
|
1951 |
+
# parse the file directly from the filesystem
|
1952 |
+
doc = _parseDocumentFromURL(_encodeFilename(source), parser)
|
1953 |
+
# fix base URL if requested
|
1954 |
+
if base_url is not None:
|
1955 |
+
base_url = _encodeFilenameUTF8(base_url)
|
1956 |
+
if doc._c_doc.URL is not NULL:
|
1957 |
+
tree.xmlFree(<char*>doc._c_doc.URL)
|
1958 |
+
doc._c_doc.URL = tree.xmlStrdup(_xcstr(base_url))
|
1959 |
+
return doc
|
1960 |
+
|
1961 |
+
if base_url is not None:
|
1962 |
+
url = base_url
|
1963 |
+
else:
|
1964 |
+
url = _getFilenameForFile(source)
|
1965 |
+
|
1966 |
+
if hasattr(source, 'getvalue') and hasattr(source, 'tell'):
|
1967 |
+
# StringIO - reading from start?
|
1968 |
+
if source.tell() == 0:
|
1969 |
+
return _parseMemoryDocument(source.getvalue(), url, parser)
|
1970 |
+
|
1971 |
+
# Support for file-like objects (urlgrabber.urlopen, ...)
|
1972 |
+
if hasattr(source, 'read'):
|
1973 |
+
return _parseFilelikeDocument(source, url, parser)
|
1974 |
+
|
1975 |
+
raise TypeError, f"cannot parse from '{python._fqtypename(source).decode('UTF-8')}'"
|
1976 |
+
|
1977 |
+
cdef _Document _parseDocumentFromURL(url, _BaseParser parser):
|
1978 |
+
c_doc = _parseDocFromFile(url, parser)
|
1979 |
+
return _documentFactory(c_doc, parser)
|
1980 |
+
|
1981 |
+
cdef _Document _parseMemoryDocument(text, url, _BaseParser parser):
|
1982 |
+
if isinstance(text, unicode):
|
1983 |
+
if _hasEncodingDeclaration(text):
|
1984 |
+
raise ValueError(
|
1985 |
+
"Unicode strings with encoding declaration are not supported. "
|
1986 |
+
"Please use bytes input or XML fragments without declaration.")
|
1987 |
+
elif not isinstance(text, bytes):
|
1988 |
+
raise ValueError, "can only parse strings"
|
1989 |
+
c_doc = _parseDoc(text, url, parser)
|
1990 |
+
return _documentFactory(c_doc, parser)
|
1991 |
+
|
1992 |
+
cdef _Document _parseFilelikeDocument(source, url, _BaseParser parser):
|
1993 |
+
c_doc = _parseDocFromFilelike(source, url, parser)
|
1994 |
+
return _documentFactory(c_doc, parser)
|
llmeval-env/lib/python3.10/site-packages/lxml/public-api.pxi
ADDED
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Public C API for lxml.etree
|
2 |
+
|
3 |
+
cdef public api _Element deepcopyNodeToDocument(_Document doc, xmlNode* c_root):
|
4 |
+
"Recursively copy the element into the document. doc is not modified."
|
5 |
+
cdef xmlNode* c_node
|
6 |
+
c_node = _copyNodeToDoc(c_root, doc._c_doc)
|
7 |
+
return _elementFactory(doc, c_node)
|
8 |
+
|
9 |
+
cdef public api _ElementTree elementTreeFactory(_Element context_node):
|
10 |
+
_assertValidNode(context_node)
|
11 |
+
return newElementTree(context_node, _ElementTree)
|
12 |
+
|
13 |
+
cdef public api _ElementTree newElementTree(_Element context_node,
|
14 |
+
object subclass):
|
15 |
+
if <void*>context_node is NULL or context_node is None:
|
16 |
+
raise TypeError
|
17 |
+
_assertValidNode(context_node)
|
18 |
+
return _newElementTree(context_node._doc, context_node, subclass)
|
19 |
+
|
20 |
+
cdef public api _ElementTree adoptExternalDocument(xmlDoc* c_doc, parser, bint is_owned):
|
21 |
+
if c_doc is NULL:
|
22 |
+
raise TypeError
|
23 |
+
doc = _adoptForeignDoc(c_doc, parser, is_owned)
|
24 |
+
return _elementTreeFactory(doc, None)
|
25 |
+
|
26 |
+
cdef public api _Element elementFactory(_Document doc, xmlNode* c_node):
|
27 |
+
if c_node is NULL or doc is None:
|
28 |
+
raise TypeError
|
29 |
+
return _elementFactory(doc, c_node)
|
30 |
+
|
31 |
+
cdef public api _Element makeElement(tag, _Document doc, parser,
|
32 |
+
text, tail, attrib, nsmap):
|
33 |
+
return _makeElement(tag, NULL, doc, parser, text, tail, attrib, nsmap, None)
|
34 |
+
|
35 |
+
cdef public api _Element makeSubElement(_Element parent, tag, text, tail,
|
36 |
+
attrib, nsmap):
|
37 |
+
_assertValidNode(parent)
|
38 |
+
return _makeSubElement(parent, tag, text, tail, attrib, nsmap, None)
|
39 |
+
|
40 |
+
cdef public api void setElementClassLookupFunction(
|
41 |
+
_element_class_lookup_function function, state):
|
42 |
+
_setElementClassLookupFunction(function, state)
|
43 |
+
|
44 |
+
cdef public api object lookupDefaultElementClass(state, doc, xmlNode* c_node):
|
45 |
+
return _lookupDefaultElementClass(state, doc, c_node)
|
46 |
+
|
47 |
+
cdef public api object lookupNamespaceElementClass(state, doc, xmlNode* c_node):
|
48 |
+
return _find_nselement_class(state, doc, c_node)
|
49 |
+
|
50 |
+
cdef public api object callLookupFallback(FallbackElementClassLookup lookup,
|
51 |
+
_Document doc, xmlNode* c_node):
|
52 |
+
return _callLookupFallback(lookup, doc, c_node)
|
53 |
+
|
54 |
+
cdef public api int tagMatches(xmlNode* c_node, const_xmlChar* c_href, const_xmlChar* c_name):
|
55 |
+
if c_node is NULL:
|
56 |
+
return -1
|
57 |
+
return _tagMatches(c_node, c_href, c_name)
|
58 |
+
|
59 |
+
cdef public api _Document documentOrRaise(object input):
|
60 |
+
return _documentOrRaise(input)
|
61 |
+
|
62 |
+
cdef public api _Element rootNodeOrRaise(object input):
|
63 |
+
return _rootNodeOrRaise(input)
|
64 |
+
|
65 |
+
cdef public api bint hasText(xmlNode* c_node):
|
66 |
+
return _hasText(c_node)
|
67 |
+
|
68 |
+
cdef public api bint hasTail(xmlNode* c_node):
|
69 |
+
return _hasTail(c_node)
|
70 |
+
|
71 |
+
cdef public api unicode textOf(xmlNode* c_node):
|
72 |
+
if c_node is NULL:
|
73 |
+
return None
|
74 |
+
return _collectText(c_node.children)
|
75 |
+
|
76 |
+
cdef public api unicode tailOf(xmlNode* c_node):
|
77 |
+
if c_node is NULL:
|
78 |
+
return None
|
79 |
+
return _collectText(c_node.next)
|
80 |
+
|
81 |
+
cdef public api int setNodeText(xmlNode* c_node, text) except -1:
|
82 |
+
if c_node is NULL:
|
83 |
+
raise ValueError
|
84 |
+
return _setNodeText(c_node, text)
|
85 |
+
|
86 |
+
cdef public api int setTailText(xmlNode* c_node, text) except -1:
|
87 |
+
if c_node is NULL:
|
88 |
+
raise ValueError
|
89 |
+
return _setTailText(c_node, text)
|
90 |
+
|
91 |
+
cdef public api unicode attributeValue(xmlNode* c_element, xmlAttr* c_attrib_node):
|
92 |
+
return _attributeValue(c_element, c_attrib_node)
|
93 |
+
|
94 |
+
cdef public api unicode attributeValueFromNsName(xmlNode* c_element,
|
95 |
+
const_xmlChar* ns, const_xmlChar* name):
|
96 |
+
return _attributeValueFromNsName(c_element, ns, name)
|
97 |
+
|
98 |
+
cdef public api object getAttributeValue(_Element element, key, default):
|
99 |
+
_assertValidNode(element)
|
100 |
+
return _getAttributeValue(element, key, default)
|
101 |
+
|
102 |
+
cdef public api object iterattributes(_Element element, int keysvalues):
|
103 |
+
_assertValidNode(element)
|
104 |
+
return _attributeIteratorFactory(element, keysvalues)
|
105 |
+
|
106 |
+
cdef public api list collectAttributes(xmlNode* c_element, int keysvalues):
|
107 |
+
return _collectAttributes(c_element, keysvalues)
|
108 |
+
|
109 |
+
cdef public api int setAttributeValue(_Element element, key, value) except -1:
|
110 |
+
_assertValidNode(element)
|
111 |
+
return _setAttributeValue(element, key, value)
|
112 |
+
|
113 |
+
cdef public api int delAttribute(_Element element, key) except -1:
|
114 |
+
_assertValidNode(element)
|
115 |
+
return _delAttribute(element, key)
|
116 |
+
|
117 |
+
cdef public api int delAttributeFromNsName(tree.xmlNode* c_element,
|
118 |
+
const_xmlChar* c_href, const_xmlChar* c_name):
|
119 |
+
return _delAttributeFromNsName(c_element, c_href, c_name)
|
120 |
+
|
121 |
+
cdef public api bint hasChild(xmlNode* c_node):
|
122 |
+
return _hasChild(c_node)
|
123 |
+
|
124 |
+
cdef public api xmlNode* findChild(xmlNode* c_node, Py_ssize_t index):
|
125 |
+
return _findChild(c_node, index)
|
126 |
+
|
127 |
+
cdef public api xmlNode* findChildForwards(xmlNode* c_node, Py_ssize_t index):
|
128 |
+
return _findChildForwards(c_node, index)
|
129 |
+
|
130 |
+
cdef public api xmlNode* findChildBackwards(xmlNode* c_node, Py_ssize_t index):
|
131 |
+
return _findChildBackwards(c_node, index)
|
132 |
+
|
133 |
+
cdef public api xmlNode* nextElement(xmlNode* c_node):
|
134 |
+
return _nextElement(c_node)
|
135 |
+
|
136 |
+
cdef public api xmlNode* previousElement(xmlNode* c_node):
|
137 |
+
return _previousElement(c_node)
|
138 |
+
|
139 |
+
cdef public api void appendChild(_Element parent, _Element child):
|
140 |
+
# deprecated, use appendChildToElement() instead!
|
141 |
+
_appendChild(parent, child)
|
142 |
+
|
143 |
+
cdef public api int appendChildToElement(_Element parent, _Element child) except -1:
|
144 |
+
return _appendChild(parent, child)
|
145 |
+
|
146 |
+
cdef public api unicode pyunicode(const_xmlChar* s):
|
147 |
+
if s is NULL:
|
148 |
+
raise TypeError
|
149 |
+
return funicode(s)
|
150 |
+
|
151 |
+
cdef public api bytes utf8(object s):
|
152 |
+
return _utf8(s)
|
153 |
+
|
154 |
+
cdef public api tuple getNsTag(object tag):
|
155 |
+
return _getNsTag(tag)
|
156 |
+
|
157 |
+
cdef public api tuple getNsTagWithEmptyNs(object tag):
|
158 |
+
return _getNsTagWithEmptyNs(tag)
|
159 |
+
|
160 |
+
cdef public api unicode namespacedName(xmlNode* c_node):
|
161 |
+
return _namespacedName(c_node)
|
162 |
+
|
163 |
+
cdef public api unicode namespacedNameFromNsName(const_xmlChar* href, const_xmlChar* name):
|
164 |
+
return _namespacedNameFromNsName(href, name)
|
165 |
+
|
166 |
+
cdef public api void iteratorStoreNext(_ElementIterator iterator, _Element node):
|
167 |
+
# deprecated!
|
168 |
+
iterator._storeNext(node)
|
169 |
+
|
170 |
+
cdef public api void initTagMatch(_ElementTagMatcher matcher, tag):
|
171 |
+
# deprecated!
|
172 |
+
matcher._initTagMatch(tag)
|
173 |
+
|
174 |
+
cdef public api tree.xmlNs* findOrBuildNodeNsPrefix(
|
175 |
+
_Document doc, xmlNode* c_node, const_xmlChar* href, const_xmlChar* prefix) except NULL:
|
176 |
+
if doc is None:
|
177 |
+
raise TypeError
|
178 |
+
return doc._findOrBuildNodeNs(c_node, href, prefix, 0)
|
llmeval-env/lib/python3.10/site-packages/lxml/readonlytree.pxi
ADDED
@@ -0,0 +1,565 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# read-only tree implementation
|
2 |
+
|
3 |
+
@cython.internal
|
4 |
+
cdef class _ReadOnlyProxy:
|
5 |
+
"A read-only proxy class suitable for PIs/Comments (for internal use only!)."
|
6 |
+
cdef bint _free_after_use
|
7 |
+
cdef xmlNode* _c_node
|
8 |
+
cdef _ReadOnlyProxy _source_proxy
|
9 |
+
cdef list _dependent_proxies
|
10 |
+
def __cinit__(self):
|
11 |
+
self._c_node = NULL
|
12 |
+
self._free_after_use = 0
|
13 |
+
|
14 |
+
cdef int _assertNode(self) except -1:
|
15 |
+
"""This is our way of saying: this proxy is invalid!
|
16 |
+
"""
|
17 |
+
if not self._c_node:
|
18 |
+
raise ReferenceError("Proxy invalidated!")
|
19 |
+
return 0
|
20 |
+
|
21 |
+
cdef int _raise_unsupported_type(self) except -1:
|
22 |
+
raise TypeError(f"Unsupported node type: {self._c_node.type}")
|
23 |
+
|
24 |
+
cdef void free_after_use(self) noexcept:
|
25 |
+
"""Should the xmlNode* be freed when releasing the proxy?
|
26 |
+
"""
|
27 |
+
self._free_after_use = 1
|
28 |
+
|
29 |
+
@property
|
30 |
+
def tag(self):
|
31 |
+
"""Element tag
|
32 |
+
"""
|
33 |
+
self._assertNode()
|
34 |
+
if self._c_node.type == tree.XML_ELEMENT_NODE:
|
35 |
+
return _namespacedName(self._c_node)
|
36 |
+
elif self._c_node.type == tree.XML_PI_NODE:
|
37 |
+
return ProcessingInstruction
|
38 |
+
elif self._c_node.type == tree.XML_COMMENT_NODE:
|
39 |
+
return Comment
|
40 |
+
elif self._c_node.type == tree.XML_ENTITY_REF_NODE:
|
41 |
+
return Entity
|
42 |
+
else:
|
43 |
+
self._raise_unsupported_type()
|
44 |
+
|
45 |
+
@property
|
46 |
+
def text(self):
|
47 |
+
"""Text before the first subelement. This is either a string or
|
48 |
+
the value None, if there was no text.
|
49 |
+
"""
|
50 |
+
self._assertNode()
|
51 |
+
if self._c_node.type == tree.XML_ELEMENT_NODE:
|
52 |
+
return _collectText(self._c_node.children)
|
53 |
+
elif self._c_node.type in (tree.XML_PI_NODE,
|
54 |
+
tree.XML_COMMENT_NODE):
|
55 |
+
if self._c_node.content is NULL:
|
56 |
+
return ''
|
57 |
+
else:
|
58 |
+
return funicode(self._c_node.content)
|
59 |
+
elif self._c_node.type == tree.XML_ENTITY_REF_NODE:
|
60 |
+
return f'&{funicode(self._c_node.name)};'
|
61 |
+
else:
|
62 |
+
self._raise_unsupported_type()
|
63 |
+
|
64 |
+
@property
|
65 |
+
def tail(self):
|
66 |
+
"""Text after this element's end tag, but before the next sibling
|
67 |
+
element's start tag. This is either a string or the value None, if
|
68 |
+
there was no text.
|
69 |
+
"""
|
70 |
+
self._assertNode()
|
71 |
+
return _collectText(self._c_node.next)
|
72 |
+
|
73 |
+
@property
|
74 |
+
def sourceline(self):
|
75 |
+
"""Original line number as found by the parser or None if unknown.
|
76 |
+
"""
|
77 |
+
cdef long line
|
78 |
+
self._assertNode()
|
79 |
+
line = tree.xmlGetLineNo(self._c_node)
|
80 |
+
if line > 0:
|
81 |
+
return line
|
82 |
+
else:
|
83 |
+
return None
|
84 |
+
|
85 |
+
def __repr__(self):
|
86 |
+
self._assertNode()
|
87 |
+
if self._c_node.type == tree.XML_ELEMENT_NODE:
|
88 |
+
return "<Element %s at 0x%x>" % (self.tag, id(self))
|
89 |
+
elif self._c_node.type == tree.XML_COMMENT_NODE:
|
90 |
+
return "<!--%s-->" % self.text
|
91 |
+
elif self._c_node.type == tree.XML_ENTITY_NODE:
|
92 |
+
return "&%s;" % funicode(self._c_node.name)
|
93 |
+
elif self._c_node.type == tree.XML_PI_NODE:
|
94 |
+
text = self.text
|
95 |
+
if text:
|
96 |
+
return "<?%s %s?>" % (self.target, text)
|
97 |
+
else:
|
98 |
+
return "<?%s?>" % self.target
|
99 |
+
else:
|
100 |
+
self._raise_unsupported_type()
|
101 |
+
|
102 |
+
def __getitem__(self, x):
|
103 |
+
"""Returns the subelement at the given position or the requested
|
104 |
+
slice.
|
105 |
+
"""
|
106 |
+
cdef xmlNode* c_node = NULL
|
107 |
+
cdef Py_ssize_t step = 0, slicelength = 0
|
108 |
+
cdef Py_ssize_t c, i
|
109 |
+
cdef _node_to_node_function next_element
|
110 |
+
cdef list result
|
111 |
+
self._assertNode()
|
112 |
+
if isinstance(x, slice):
|
113 |
+
# slicing
|
114 |
+
if _isFullSlice(<slice>x):
|
115 |
+
return _collectChildren(self)
|
116 |
+
_findChildSlice(<slice>x, self._c_node, &c_node, &step, &slicelength)
|
117 |
+
if c_node is NULL:
|
118 |
+
return []
|
119 |
+
if step > 0:
|
120 |
+
next_element = _nextElement
|
121 |
+
else:
|
122 |
+
step = -step
|
123 |
+
next_element = _previousElement
|
124 |
+
result = []
|
125 |
+
c = 0
|
126 |
+
while c_node is not NULL and c < slicelength:
|
127 |
+
result.append(_newReadOnlyProxy(self._source_proxy, c_node))
|
128 |
+
result.append(_elementFactory(self._doc, c_node))
|
129 |
+
c = c + 1
|
130 |
+
for i from 0 <= i < step:
|
131 |
+
c_node = next_element(c_node)
|
132 |
+
return result
|
133 |
+
else:
|
134 |
+
# indexing
|
135 |
+
c_node = _findChild(self._c_node, x)
|
136 |
+
if c_node is NULL:
|
137 |
+
raise IndexError, "list index out of range"
|
138 |
+
return _newReadOnlyProxy(self._source_proxy, c_node)
|
139 |
+
|
140 |
+
def __len__(self):
|
141 |
+
"""Returns the number of subelements.
|
142 |
+
"""
|
143 |
+
cdef Py_ssize_t c
|
144 |
+
cdef xmlNode* c_node
|
145 |
+
self._assertNode()
|
146 |
+
c = 0
|
147 |
+
c_node = self._c_node.children
|
148 |
+
while c_node is not NULL:
|
149 |
+
if tree._isElement(c_node):
|
150 |
+
c = c + 1
|
151 |
+
c_node = c_node.next
|
152 |
+
return c
|
153 |
+
|
154 |
+
def __bool__(self):
|
155 |
+
cdef xmlNode* c_node
|
156 |
+
self._assertNode()
|
157 |
+
c_node = _findChildBackwards(self._c_node, 0)
|
158 |
+
return c_node != NULL
|
159 |
+
|
160 |
+
def __deepcopy__(self, memo):
|
161 |
+
"__deepcopy__(self, memo)"
|
162 |
+
return self.__copy__()
|
163 |
+
|
164 |
+
cpdef __copy__(self):
|
165 |
+
"__copy__(self)"
|
166 |
+
cdef xmlDoc* c_doc
|
167 |
+
cdef xmlNode* c_node
|
168 |
+
cdef _Document new_doc
|
169 |
+
if self._c_node is NULL:
|
170 |
+
return self
|
171 |
+
c_doc = _copyDocRoot(self._c_node.doc, self._c_node) # recursive
|
172 |
+
new_doc = _documentFactory(c_doc, None)
|
173 |
+
root = new_doc.getroot()
|
174 |
+
if root is not None:
|
175 |
+
return root
|
176 |
+
# Comment/PI
|
177 |
+
c_node = c_doc.children
|
178 |
+
while c_node is not NULL and c_node.type != self._c_node.type:
|
179 |
+
c_node = c_node.next
|
180 |
+
if c_node is NULL:
|
181 |
+
return None
|
182 |
+
return _elementFactory(new_doc, c_node)
|
183 |
+
|
184 |
+
def __iter__(self):
|
185 |
+
return iter(self.getchildren())
|
186 |
+
|
187 |
+
def iterchildren(self, tag=None, *, reversed=False):
|
188 |
+
"""iterchildren(self, tag=None, reversed=False)
|
189 |
+
|
190 |
+
Iterate over the children of this element.
|
191 |
+
"""
|
192 |
+
children = self.getchildren()
|
193 |
+
if tag is not None and tag != '*':
|
194 |
+
children = [ el for el in children if el.tag == tag ]
|
195 |
+
if reversed:
|
196 |
+
children = children[::-1]
|
197 |
+
return iter(children)
|
198 |
+
|
199 |
+
cpdef getchildren(self):
|
200 |
+
"""Returns all subelements. The elements are returned in document
|
201 |
+
order.
|
202 |
+
"""
|
203 |
+
cdef xmlNode* c_node
|
204 |
+
cdef list result
|
205 |
+
self._assertNode()
|
206 |
+
result = []
|
207 |
+
c_node = self._c_node.children
|
208 |
+
while c_node is not NULL:
|
209 |
+
if tree._isElement(c_node):
|
210 |
+
result.append(_newReadOnlyProxy(self._source_proxy, c_node))
|
211 |
+
c_node = c_node.next
|
212 |
+
return result
|
213 |
+
|
214 |
+
def getparent(self):
|
215 |
+
"""Returns the parent of this element or None for the root element.
|
216 |
+
"""
|
217 |
+
cdef xmlNode* c_parent
|
218 |
+
self._assertNode()
|
219 |
+
c_parent = self._c_node.parent
|
220 |
+
if c_parent is NULL or not tree._isElement(c_parent):
|
221 |
+
return None
|
222 |
+
else:
|
223 |
+
return _newReadOnlyProxy(self._source_proxy, c_parent)
|
224 |
+
|
225 |
+
def getnext(self):
|
226 |
+
"""Returns the following sibling of this element or None.
|
227 |
+
"""
|
228 |
+
cdef xmlNode* c_node
|
229 |
+
self._assertNode()
|
230 |
+
c_node = _nextElement(self._c_node)
|
231 |
+
if c_node is not NULL:
|
232 |
+
return _newReadOnlyProxy(self._source_proxy, c_node)
|
233 |
+
return None
|
234 |
+
|
235 |
+
def getprevious(self):
|
236 |
+
"""Returns the preceding sibling of this element or None.
|
237 |
+
"""
|
238 |
+
cdef xmlNode* c_node
|
239 |
+
self._assertNode()
|
240 |
+
c_node = _previousElement(self._c_node)
|
241 |
+
if c_node is not NULL:
|
242 |
+
return _newReadOnlyProxy(self._source_proxy, c_node)
|
243 |
+
return None
|
244 |
+
|
245 |
+
|
246 |
+
@cython.final
|
247 |
+
@cython.internal
|
248 |
+
cdef class _ReadOnlyPIProxy(_ReadOnlyProxy):
|
249 |
+
"""A read-only proxy for processing instructions (for internal use only!)"""
|
250 |
+
@property
|
251 |
+
def target(self):
|
252 |
+
self._assertNode()
|
253 |
+
return funicode(self._c_node.name)
|
254 |
+
|
255 |
+
@cython.final
|
256 |
+
@cython.internal
|
257 |
+
cdef class _ReadOnlyEntityProxy(_ReadOnlyProxy):
|
258 |
+
"""A read-only proxy for entity references (for internal use only!)"""
|
259 |
+
property name:
|
260 |
+
def __get__(self):
|
261 |
+
return funicode(self._c_node.name)
|
262 |
+
|
263 |
+
def __set__(self, value):
|
264 |
+
value_utf = _utf8(value)
|
265 |
+
if '&' in value or ';' in value:
|
266 |
+
raise ValueError(f"Invalid entity name '{value}'")
|
267 |
+
tree.xmlNodeSetName(self._c_node, _xcstr(value_utf))
|
268 |
+
|
269 |
+
@property
|
270 |
+
def text(self):
|
271 |
+
return f'&{funicode(self._c_node.name)};'
|
272 |
+
|
273 |
+
|
274 |
+
@cython.internal
|
275 |
+
cdef class _ReadOnlyElementProxy(_ReadOnlyProxy):
|
276 |
+
"""The main read-only Element proxy class (for internal use only!)."""
|
277 |
+
|
278 |
+
@property
|
279 |
+
def attrib(self):
|
280 |
+
self._assertNode()
|
281 |
+
return dict(_collectAttributes(self._c_node, 3))
|
282 |
+
|
283 |
+
@property
|
284 |
+
def prefix(self):
|
285 |
+
"""Namespace prefix or None.
|
286 |
+
"""
|
287 |
+
self._assertNode()
|
288 |
+
if self._c_node.ns is not NULL:
|
289 |
+
if self._c_node.ns.prefix is not NULL:
|
290 |
+
return funicode(self._c_node.ns.prefix)
|
291 |
+
return None
|
292 |
+
|
293 |
+
@property
|
294 |
+
def nsmap(self):
|
295 |
+
"""Namespace prefix->URI mapping known in the context of this
|
296 |
+
Element. This includes all namespace declarations of the
|
297 |
+
parents.
|
298 |
+
|
299 |
+
Note that changing the returned dict has no effect on the Element.
|
300 |
+
"""
|
301 |
+
self._assertNode()
|
302 |
+
return _build_nsmap(self._c_node)
|
303 |
+
|
304 |
+
def get(self, key, default=None):
|
305 |
+
"""Gets an element attribute.
|
306 |
+
"""
|
307 |
+
self._assertNode()
|
308 |
+
return _getNodeAttributeValue(self._c_node, key, default)
|
309 |
+
|
310 |
+
def keys(self):
|
311 |
+
"""Gets a list of attribute names. The names are returned in an
|
312 |
+
arbitrary order (just like for an ordinary Python dictionary).
|
313 |
+
"""
|
314 |
+
self._assertNode()
|
315 |
+
return _collectAttributes(self._c_node, 1)
|
316 |
+
|
317 |
+
def values(self):
|
318 |
+
"""Gets element attributes, as a sequence. The attributes are returned
|
319 |
+
in an arbitrary order.
|
320 |
+
"""
|
321 |
+
self._assertNode()
|
322 |
+
return _collectAttributes(self._c_node, 2)
|
323 |
+
|
324 |
+
def items(self):
|
325 |
+
"""Gets element attributes, as a sequence. The attributes are returned
|
326 |
+
in an arbitrary order.
|
327 |
+
"""
|
328 |
+
self._assertNode()
|
329 |
+
return _collectAttributes(self._c_node, 3)
|
330 |
+
|
331 |
+
cdef _ReadOnlyProxy _newReadOnlyProxy(
|
332 |
+
_ReadOnlyProxy source_proxy, xmlNode* c_node):
|
333 |
+
cdef _ReadOnlyProxy el
|
334 |
+
if c_node.type == tree.XML_ELEMENT_NODE:
|
335 |
+
el = _ReadOnlyElementProxy.__new__(_ReadOnlyElementProxy)
|
336 |
+
elif c_node.type == tree.XML_PI_NODE:
|
337 |
+
el = _ReadOnlyPIProxy.__new__(_ReadOnlyPIProxy)
|
338 |
+
elif c_node.type in (tree.XML_COMMENT_NODE,
|
339 |
+
tree.XML_ENTITY_REF_NODE):
|
340 |
+
el = _ReadOnlyProxy.__new__(_ReadOnlyProxy)
|
341 |
+
else:
|
342 |
+
raise TypeError(f"Unsupported element type: {c_node.type}")
|
343 |
+
el._c_node = c_node
|
344 |
+
_initReadOnlyProxy(el, source_proxy)
|
345 |
+
return el
|
346 |
+
|
347 |
+
cdef inline _initReadOnlyProxy(_ReadOnlyProxy el,
|
348 |
+
_ReadOnlyProxy source_proxy):
|
349 |
+
if source_proxy is None:
|
350 |
+
el._source_proxy = el
|
351 |
+
el._dependent_proxies = [el]
|
352 |
+
else:
|
353 |
+
el._source_proxy = source_proxy
|
354 |
+
source_proxy._dependent_proxies.append(el)
|
355 |
+
|
356 |
+
cdef _freeReadOnlyProxies(_ReadOnlyProxy sourceProxy):
|
357 |
+
cdef xmlNode* c_node
|
358 |
+
cdef _ReadOnlyProxy el
|
359 |
+
if sourceProxy is None:
|
360 |
+
return
|
361 |
+
if sourceProxy._dependent_proxies is None:
|
362 |
+
return
|
363 |
+
for el in sourceProxy._dependent_proxies:
|
364 |
+
c_node = el._c_node
|
365 |
+
el._c_node = NULL
|
366 |
+
if el._free_after_use:
|
367 |
+
tree.xmlFreeNode(c_node)
|
368 |
+
del sourceProxy._dependent_proxies[:]
|
369 |
+
|
370 |
+
# opaque wrapper around non-element nodes, e.g. the document node
|
371 |
+
#
|
372 |
+
# This class does not imply any restrictions on modifiability or
|
373 |
+
# read-only status of the node, so use with caution.
|
374 |
+
|
375 |
+
@cython.internal
|
376 |
+
cdef class _OpaqueNodeWrapper:
|
377 |
+
cdef tree.xmlNode* _c_node
|
378 |
+
def __init__(self):
|
379 |
+
raise TypeError, "This type cannot be instantiated from Python"
|
380 |
+
|
381 |
+
@cython.final
|
382 |
+
@cython.internal
|
383 |
+
cdef class _OpaqueDocumentWrapper(_OpaqueNodeWrapper):
|
384 |
+
cdef int _assertNode(self) except -1:
|
385 |
+
"""This is our way of saying: this proxy is invalid!
|
386 |
+
"""
|
387 |
+
assert self._c_node is not NULL, "Proxy invalidated!"
|
388 |
+
return 0
|
389 |
+
|
390 |
+
cpdef append(self, other_element):
|
391 |
+
"""Append a copy of an Element to the list of children.
|
392 |
+
"""
|
393 |
+
cdef xmlNode* c_next
|
394 |
+
cdef xmlNode* c_node
|
395 |
+
self._assertNode()
|
396 |
+
c_node = _roNodeOf(other_element)
|
397 |
+
if c_node.type == tree.XML_ELEMENT_NODE:
|
398 |
+
if tree.xmlDocGetRootElement(<tree.xmlDoc*>self._c_node) is not NULL:
|
399 |
+
raise ValueError, "cannot append, document already has a root element"
|
400 |
+
elif c_node.type not in (tree.XML_PI_NODE, tree.XML_COMMENT_NODE):
|
401 |
+
raise TypeError, f"unsupported element type for top-level node: {c_node.type}"
|
402 |
+
c_node = _copyNodeToDoc(c_node, <tree.xmlDoc*>self._c_node)
|
403 |
+
c_next = c_node.next
|
404 |
+
tree.xmlAddChild(self._c_node, c_node)
|
405 |
+
_moveTail(c_next, c_node)
|
406 |
+
|
407 |
+
def extend(self, elements):
|
408 |
+
"""Append a copy of all Elements from a sequence to the list of
|
409 |
+
children.
|
410 |
+
"""
|
411 |
+
self._assertNode()
|
412 |
+
for element in elements:
|
413 |
+
self.append(element)
|
414 |
+
|
415 |
+
cdef _OpaqueNodeWrapper _newOpaqueAppendOnlyNodeWrapper(xmlNode* c_node):
|
416 |
+
cdef _OpaqueNodeWrapper node
|
417 |
+
if c_node.type in (tree.XML_DOCUMENT_NODE, tree.XML_HTML_DOCUMENT_NODE):
|
418 |
+
node = _OpaqueDocumentWrapper.__new__(_OpaqueDocumentWrapper)
|
419 |
+
else:
|
420 |
+
node = _OpaqueNodeWrapper.__new__(_OpaqueNodeWrapper)
|
421 |
+
node._c_node = c_node
|
422 |
+
return node
|
423 |
+
|
424 |
+
# element proxies that allow restricted modification
|
425 |
+
|
426 |
+
@cython.internal
|
427 |
+
cdef class _ModifyContentOnlyProxy(_ReadOnlyProxy):
|
428 |
+
"""A read-only proxy that allows changing the text content.
|
429 |
+
"""
|
430 |
+
property text:
|
431 |
+
def __get__(self):
|
432 |
+
self._assertNode()
|
433 |
+
if self._c_node.content is NULL:
|
434 |
+
return ''
|
435 |
+
else:
|
436 |
+
return funicode(self._c_node.content)
|
437 |
+
|
438 |
+
def __set__(self, value):
|
439 |
+
cdef tree.xmlDict* c_dict
|
440 |
+
self._assertNode()
|
441 |
+
if value is None:
|
442 |
+
c_text = <const_xmlChar*>NULL
|
443 |
+
else:
|
444 |
+
value = _utf8(value)
|
445 |
+
c_text = _xcstr(value)
|
446 |
+
tree.xmlNodeSetContent(self._c_node, c_text)
|
447 |
+
|
448 |
+
@cython.final
|
449 |
+
@cython.internal
|
450 |
+
cdef class _ModifyContentOnlyPIProxy(_ModifyContentOnlyProxy):
|
451 |
+
"""A read-only proxy that allows changing the text/target content of a
|
452 |
+
processing instruction.
|
453 |
+
"""
|
454 |
+
property target:
|
455 |
+
def __get__(self):
|
456 |
+
self._assertNode()
|
457 |
+
return funicode(self._c_node.name)
|
458 |
+
|
459 |
+
def __set__(self, value):
|
460 |
+
self._assertNode()
|
461 |
+
value = _utf8(value)
|
462 |
+
c_text = _xcstr(value)
|
463 |
+
tree.xmlNodeSetName(self._c_node, c_text)
|
464 |
+
|
465 |
+
@cython.final
|
466 |
+
@cython.internal
|
467 |
+
cdef class _ModifyContentOnlyEntityProxy(_ModifyContentOnlyProxy):
|
468 |
+
"A read-only proxy for entity references (for internal use only!)"
|
469 |
+
property name:
|
470 |
+
def __get__(self):
|
471 |
+
return funicode(self._c_node.name)
|
472 |
+
|
473 |
+
def __set__(self, value):
|
474 |
+
value = _utf8(value)
|
475 |
+
assert '&' not in value and ';' not in value, \
|
476 |
+
f"Invalid entity name '{value}'"
|
477 |
+
c_text = _xcstr(value)
|
478 |
+
tree.xmlNodeSetName(self._c_node, c_text)
|
479 |
+
|
480 |
+
|
481 |
+
@cython.final
|
482 |
+
@cython.internal
|
483 |
+
cdef class _AppendOnlyElementProxy(_ReadOnlyElementProxy):
|
484 |
+
"""A read-only element that allows adding children and changing the
|
485 |
+
text content (i.e. everything that adds to the subtree).
|
486 |
+
"""
|
487 |
+
cpdef append(self, other_element):
|
488 |
+
"""Append a copy of an Element to the list of children.
|
489 |
+
"""
|
490 |
+
cdef xmlNode* c_next
|
491 |
+
cdef xmlNode* c_node
|
492 |
+
self._assertNode()
|
493 |
+
c_node = _roNodeOf(other_element)
|
494 |
+
c_node = _copyNodeToDoc(c_node, self._c_node.doc)
|
495 |
+
c_next = c_node.next
|
496 |
+
tree.xmlAddChild(self._c_node, c_node)
|
497 |
+
_moveTail(c_next, c_node)
|
498 |
+
|
499 |
+
def extend(self, elements):
|
500 |
+
"""Append a copy of all Elements from a sequence to the list of
|
501 |
+
children.
|
502 |
+
"""
|
503 |
+
self._assertNode()
|
504 |
+
for element in elements:
|
505 |
+
self.append(element)
|
506 |
+
|
507 |
+
property text:
|
508 |
+
"""Text before the first subelement. This is either a string or the
|
509 |
+
value None, if there was no text.
|
510 |
+
"""
|
511 |
+
def __get__(self):
|
512 |
+
self._assertNode()
|
513 |
+
return _collectText(self._c_node.children)
|
514 |
+
|
515 |
+
def __set__(self, value):
|
516 |
+
self._assertNode()
|
517 |
+
if isinstance(value, QName):
|
518 |
+
value = _resolveQNameText(self, value).decode('utf8')
|
519 |
+
_setNodeText(self._c_node, value)
|
520 |
+
|
521 |
+
|
522 |
+
cdef _ReadOnlyProxy _newAppendOnlyProxy(
|
523 |
+
_ReadOnlyProxy source_proxy, xmlNode* c_node):
|
524 |
+
cdef _ReadOnlyProxy el
|
525 |
+
if c_node.type == tree.XML_ELEMENT_NODE:
|
526 |
+
el = _AppendOnlyElementProxy.__new__(_AppendOnlyElementProxy)
|
527 |
+
elif c_node.type == tree.XML_PI_NODE:
|
528 |
+
el = _ModifyContentOnlyPIProxy.__new__(_ModifyContentOnlyPIProxy)
|
529 |
+
elif c_node.type == tree.XML_COMMENT_NODE:
|
530 |
+
el = _ModifyContentOnlyProxy.__new__(_ModifyContentOnlyProxy)
|
531 |
+
else:
|
532 |
+
raise TypeError(f"Unsupported element type: {c_node.type}")
|
533 |
+
el._c_node = c_node
|
534 |
+
_initReadOnlyProxy(el, source_proxy)
|
535 |
+
return el
|
536 |
+
|
537 |
+
cdef xmlNode* _roNodeOf(element) except NULL:
|
538 |
+
cdef xmlNode* c_node
|
539 |
+
if isinstance(element, _Element):
|
540 |
+
c_node = (<_Element>element)._c_node
|
541 |
+
elif isinstance(element, _ReadOnlyProxy):
|
542 |
+
c_node = (<_ReadOnlyProxy>element)._c_node
|
543 |
+
elif isinstance(element, _OpaqueNodeWrapper):
|
544 |
+
c_node = (<_OpaqueNodeWrapper>element)._c_node
|
545 |
+
else:
|
546 |
+
raise TypeError, f"invalid argument type {type(element)}"
|
547 |
+
|
548 |
+
if c_node is NULL:
|
549 |
+
raise TypeError, "invalid element"
|
550 |
+
return c_node
|
551 |
+
|
552 |
+
cdef xmlNode* _nonRoNodeOf(element) except NULL:
|
553 |
+
cdef xmlNode* c_node
|
554 |
+
if isinstance(element, _Element):
|
555 |
+
c_node = (<_Element>element)._c_node
|
556 |
+
elif isinstance(element, _AppendOnlyElementProxy):
|
557 |
+
c_node = (<_AppendOnlyElementProxy>element)._c_node
|
558 |
+
elif isinstance(element, _OpaqueNodeWrapper):
|
559 |
+
c_node = (<_OpaqueNodeWrapper>element)._c_node
|
560 |
+
else:
|
561 |
+
raise TypeError, f"invalid argument type {type(element)}"
|
562 |
+
|
563 |
+
if c_node is NULL:
|
564 |
+
raise TypeError, "invalid element"
|
565 |
+
return c_node
|
llmeval-env/lib/python3.10/site-packages/lxml/relaxng.pxi
ADDED
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# support for RelaxNG validation
|
2 |
+
from lxml.includes cimport relaxng
|
3 |
+
|
4 |
+
cdef object _rnc2rng
|
5 |
+
try:
|
6 |
+
import rnc2rng as _rnc2rng
|
7 |
+
except ImportError:
|
8 |
+
_rnc2rng = None
|
9 |
+
|
10 |
+
|
11 |
+
cdef int _require_rnc2rng() except -1:
|
12 |
+
if _rnc2rng is None:
|
13 |
+
raise RelaxNGParseError(
|
14 |
+
'compact syntax not supported (please install rnc2rng)')
|
15 |
+
return 0
|
16 |
+
|
17 |
+
|
18 |
+
cdef class RelaxNGError(LxmlError):
|
19 |
+
"""Base class for RelaxNG errors.
|
20 |
+
"""
|
21 |
+
|
22 |
+
cdef class RelaxNGParseError(RelaxNGError):
|
23 |
+
"""Error while parsing an XML document as RelaxNG.
|
24 |
+
"""
|
25 |
+
|
26 |
+
cdef class RelaxNGValidateError(RelaxNGError):
|
27 |
+
"""Error while validating an XML document with a RelaxNG schema.
|
28 |
+
"""
|
29 |
+
|
30 |
+
|
31 |
+
################################################################################
|
32 |
+
# RelaxNG
|
33 |
+
|
34 |
+
cdef class RelaxNG(_Validator):
|
35 |
+
"""RelaxNG(self, etree=None, file=None)
|
36 |
+
Turn a document into a Relax NG validator.
|
37 |
+
|
38 |
+
Either pass a schema as Element or ElementTree, or pass a file or
|
39 |
+
filename through the ``file`` keyword argument.
|
40 |
+
"""
|
41 |
+
cdef relaxng.xmlRelaxNG* _c_schema
|
42 |
+
def __cinit__(self):
|
43 |
+
self._c_schema = NULL
|
44 |
+
|
45 |
+
def __init__(self, etree=None, *, file=None):
|
46 |
+
cdef _Document doc
|
47 |
+
cdef _Element root_node
|
48 |
+
cdef xmlDoc* fake_c_doc = NULL
|
49 |
+
cdef relaxng.xmlRelaxNGParserCtxt* parser_ctxt = NULL
|
50 |
+
_Validator.__init__(self)
|
51 |
+
if etree is not None:
|
52 |
+
doc = _documentOrRaise(etree)
|
53 |
+
root_node = _rootNodeOrRaise(etree)
|
54 |
+
fake_c_doc = _fakeRootDoc(doc._c_doc, root_node._c_node)
|
55 |
+
parser_ctxt = relaxng.xmlRelaxNGNewDocParserCtxt(fake_c_doc)
|
56 |
+
elif file is not None:
|
57 |
+
if _isString(file):
|
58 |
+
if file[-4:].lower() == '.rnc':
|
59 |
+
_require_rnc2rng()
|
60 |
+
rng_data_utf8 = _utf8(_rnc2rng.dumps(_rnc2rng.load(file)))
|
61 |
+
doc = _parseMemoryDocument(rng_data_utf8, parser=None, url=file)
|
62 |
+
parser_ctxt = relaxng.xmlRelaxNGNewDocParserCtxt(doc._c_doc)
|
63 |
+
else:
|
64 |
+
doc = None
|
65 |
+
filename = _encodeFilename(file)
|
66 |
+
with self._error_log:
|
67 |
+
orig_loader = _register_document_loader()
|
68 |
+
parser_ctxt = relaxng.xmlRelaxNGNewParserCtxt(_cstr(filename))
|
69 |
+
_reset_document_loader(orig_loader)
|
70 |
+
elif (_getFilenameForFile(file) or '')[-4:].lower() == '.rnc':
|
71 |
+
_require_rnc2rng()
|
72 |
+
rng_data_utf8 = _utf8(_rnc2rng.dumps(_rnc2rng.load(file)))
|
73 |
+
doc = _parseMemoryDocument(
|
74 |
+
rng_data_utf8, parser=None, url=_getFilenameForFile(file))
|
75 |
+
parser_ctxt = relaxng.xmlRelaxNGNewDocParserCtxt(doc._c_doc)
|
76 |
+
else:
|
77 |
+
doc = _parseDocument(file, parser=None, base_url=None)
|
78 |
+
parser_ctxt = relaxng.xmlRelaxNGNewDocParserCtxt(doc._c_doc)
|
79 |
+
else:
|
80 |
+
raise RelaxNGParseError, "No tree or file given"
|
81 |
+
|
82 |
+
if parser_ctxt is NULL:
|
83 |
+
if fake_c_doc is not NULL:
|
84 |
+
_destroyFakeDoc(doc._c_doc, fake_c_doc)
|
85 |
+
raise RelaxNGParseError(
|
86 |
+
self._error_log._buildExceptionMessage(
|
87 |
+
"Document is not parsable as Relax NG"),
|
88 |
+
self._error_log)
|
89 |
+
|
90 |
+
# Need a cast here because older libxml2 releases do not use 'const' in the functype.
|
91 |
+
relaxng.xmlRelaxNGSetParserStructuredErrors(
|
92 |
+
parser_ctxt, <xmlerror.xmlStructuredErrorFunc> _receiveError, <void*>self._error_log)
|
93 |
+
_connectGenericErrorLog(self._error_log, xmlerror.XML_FROM_RELAXNGP)
|
94 |
+
self._c_schema = relaxng.xmlRelaxNGParse(parser_ctxt)
|
95 |
+
_connectGenericErrorLog(None)
|
96 |
+
|
97 |
+
relaxng.xmlRelaxNGFreeParserCtxt(parser_ctxt)
|
98 |
+
if self._c_schema is NULL:
|
99 |
+
if fake_c_doc is not NULL:
|
100 |
+
_destroyFakeDoc(doc._c_doc, fake_c_doc)
|
101 |
+
raise RelaxNGParseError(
|
102 |
+
self._error_log._buildExceptionMessage(
|
103 |
+
"Document is not valid Relax NG"),
|
104 |
+
self._error_log)
|
105 |
+
if fake_c_doc is not NULL:
|
106 |
+
_destroyFakeDoc(doc._c_doc, fake_c_doc)
|
107 |
+
|
108 |
+
def __dealloc__(self):
|
109 |
+
relaxng.xmlRelaxNGFree(self._c_schema)
|
110 |
+
|
111 |
+
def __call__(self, etree):
|
112 |
+
"""__call__(self, etree)
|
113 |
+
|
114 |
+
Validate doc using Relax NG.
|
115 |
+
|
116 |
+
Returns true if document is valid, false if not."""
|
117 |
+
cdef _Document doc
|
118 |
+
cdef _Element root_node
|
119 |
+
cdef xmlDoc* c_doc
|
120 |
+
cdef relaxng.xmlRelaxNGValidCtxt* valid_ctxt
|
121 |
+
cdef int ret
|
122 |
+
|
123 |
+
assert self._c_schema is not NULL, "RelaxNG instance not initialised"
|
124 |
+
doc = _documentOrRaise(etree)
|
125 |
+
root_node = _rootNodeOrRaise(etree)
|
126 |
+
|
127 |
+
valid_ctxt = relaxng.xmlRelaxNGNewValidCtxt(self._c_schema)
|
128 |
+
if valid_ctxt is NULL:
|
129 |
+
raise MemoryError()
|
130 |
+
|
131 |
+
try:
|
132 |
+
self._error_log.clear()
|
133 |
+
# Need a cast here because older libxml2 releases do not use 'const' in the functype.
|
134 |
+
relaxng.xmlRelaxNGSetValidStructuredErrors(
|
135 |
+
valid_ctxt, <xmlerror.xmlStructuredErrorFunc> _receiveError, <void*>self._error_log)
|
136 |
+
_connectGenericErrorLog(self._error_log, xmlerror.XML_FROM_RELAXNGV)
|
137 |
+
c_doc = _fakeRootDoc(doc._c_doc, root_node._c_node)
|
138 |
+
with nogil:
|
139 |
+
ret = relaxng.xmlRelaxNGValidateDoc(valid_ctxt, c_doc)
|
140 |
+
_destroyFakeDoc(doc._c_doc, c_doc)
|
141 |
+
finally:
|
142 |
+
_connectGenericErrorLog(None)
|
143 |
+
relaxng.xmlRelaxNGFreeValidCtxt(valid_ctxt)
|
144 |
+
|
145 |
+
if ret == -1:
|
146 |
+
raise RelaxNGValidateError(
|
147 |
+
"Internal error in Relax NG validation",
|
148 |
+
self._error_log)
|
149 |
+
if ret == 0:
|
150 |
+
return True
|
151 |
+
else:
|
152 |
+
return False
|
153 |
+
|
154 |
+
@classmethod
|
155 |
+
def from_rnc_string(cls, src, base_url=None):
|
156 |
+
"""Parse a RelaxNG schema in compact syntax from a text string
|
157 |
+
|
158 |
+
Requires the rnc2rng package to be installed.
|
159 |
+
|
160 |
+
Passing the source URL or file path of the source as 'base_url'
|
161 |
+
will enable resolving resource references relative to the source.
|
162 |
+
"""
|
163 |
+
_require_rnc2rng()
|
164 |
+
rng_str = utf8(_rnc2rng.dumps(_rnc2rng.loads(src)))
|
165 |
+
return cls(_parseMemoryDocument(rng_str, parser=None, url=base_url))
|
llmeval-env/lib/python3.10/site-packages/lxml/sax.py
ADDED
@@ -0,0 +1,275 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# cython: language_level=2
|
2 |
+
|
3 |
+
"""
|
4 |
+
SAX-based adapter to copy trees from/to the Python standard library.
|
5 |
+
|
6 |
+
Use the `ElementTreeContentHandler` class to build an ElementTree from
|
7 |
+
SAX events.
|
8 |
+
|
9 |
+
Use the `ElementTreeProducer` class or the `saxify()` function to fire
|
10 |
+
the SAX events of an ElementTree against a SAX ContentHandler.
|
11 |
+
|
12 |
+
See https://lxml.de/sax.html
|
13 |
+
"""
|
14 |
+
|
15 |
+
|
16 |
+
from xml.sax.handler import ContentHandler
|
17 |
+
from lxml import etree
|
18 |
+
from lxml.etree import ElementTree, SubElement
|
19 |
+
from lxml.etree import Comment, ProcessingInstruction
|
20 |
+
|
21 |
+
|
22 |
+
class SaxError(etree.LxmlError):
|
23 |
+
"""General SAX error.
|
24 |
+
"""
|
25 |
+
|
26 |
+
|
27 |
+
def _getNsTag(tag):
|
28 |
+
if tag[0] == '{':
|
29 |
+
return tuple(tag[1:].split('}', 1))
|
30 |
+
else:
|
31 |
+
return None, tag
|
32 |
+
|
33 |
+
|
34 |
+
class ElementTreeContentHandler(ContentHandler):
|
35 |
+
"""Build an lxml ElementTree from SAX events.
|
36 |
+
"""
|
37 |
+
def __init__(self, makeelement=None):
|
38 |
+
ContentHandler.__init__(self)
|
39 |
+
self._root = None
|
40 |
+
self._root_siblings = []
|
41 |
+
self._element_stack = []
|
42 |
+
self._default_ns = None
|
43 |
+
self._ns_mapping = { None : [None] }
|
44 |
+
self._new_mappings = {}
|
45 |
+
if makeelement is None:
|
46 |
+
makeelement = etree.Element
|
47 |
+
self._makeelement = makeelement
|
48 |
+
|
49 |
+
def _get_etree(self):
|
50 |
+
"Contains the generated ElementTree after parsing is finished."
|
51 |
+
return ElementTree(self._root)
|
52 |
+
|
53 |
+
etree = property(_get_etree, doc=_get_etree.__doc__)
|
54 |
+
|
55 |
+
def setDocumentLocator(self, locator):
|
56 |
+
pass
|
57 |
+
|
58 |
+
def startDocument(self):
|
59 |
+
pass
|
60 |
+
|
61 |
+
def endDocument(self):
|
62 |
+
pass
|
63 |
+
|
64 |
+
def startPrefixMapping(self, prefix, uri):
|
65 |
+
self._new_mappings[prefix] = uri
|
66 |
+
try:
|
67 |
+
self._ns_mapping[prefix].append(uri)
|
68 |
+
except KeyError:
|
69 |
+
self._ns_mapping[prefix] = [uri]
|
70 |
+
if prefix is None:
|
71 |
+
self._default_ns = uri
|
72 |
+
|
73 |
+
def endPrefixMapping(self, prefix):
|
74 |
+
ns_uri_list = self._ns_mapping[prefix]
|
75 |
+
ns_uri_list.pop()
|
76 |
+
if prefix is None:
|
77 |
+
self._default_ns = ns_uri_list[-1]
|
78 |
+
|
79 |
+
def _buildTag(self, ns_name_tuple):
|
80 |
+
ns_uri, local_name = ns_name_tuple
|
81 |
+
if ns_uri:
|
82 |
+
el_tag = "{%s}%s" % ns_name_tuple
|
83 |
+
elif self._default_ns:
|
84 |
+
el_tag = "{%s}%s" % (self._default_ns, local_name)
|
85 |
+
else:
|
86 |
+
el_tag = local_name
|
87 |
+
return el_tag
|
88 |
+
|
89 |
+
def startElementNS(self, ns_name, qname, attributes=None):
|
90 |
+
el_name = self._buildTag(ns_name)
|
91 |
+
if attributes:
|
92 |
+
attrs = {}
|
93 |
+
try:
|
94 |
+
iter_attributes = attributes.iteritems()
|
95 |
+
except AttributeError:
|
96 |
+
iter_attributes = attributes.items()
|
97 |
+
|
98 |
+
for name_tuple, value in iter_attributes:
|
99 |
+
if name_tuple[0]:
|
100 |
+
attr_name = "{%s}%s" % name_tuple
|
101 |
+
else:
|
102 |
+
attr_name = name_tuple[1]
|
103 |
+
attrs[attr_name] = value
|
104 |
+
else:
|
105 |
+
attrs = None
|
106 |
+
|
107 |
+
element_stack = self._element_stack
|
108 |
+
if self._root is None:
|
109 |
+
element = self._root = \
|
110 |
+
self._makeelement(el_name, attrs, self._new_mappings)
|
111 |
+
if self._root_siblings and hasattr(element, 'addprevious'):
|
112 |
+
for sibling in self._root_siblings:
|
113 |
+
element.addprevious(sibling)
|
114 |
+
del self._root_siblings[:]
|
115 |
+
else:
|
116 |
+
element = SubElement(element_stack[-1], el_name,
|
117 |
+
attrs, self._new_mappings)
|
118 |
+
element_stack.append(element)
|
119 |
+
|
120 |
+
self._new_mappings.clear()
|
121 |
+
|
122 |
+
def processingInstruction(self, target, data):
|
123 |
+
pi = ProcessingInstruction(target, data)
|
124 |
+
if self._root is None:
|
125 |
+
self._root_siblings.append(pi)
|
126 |
+
else:
|
127 |
+
self._element_stack[-1].append(pi)
|
128 |
+
|
129 |
+
def endElementNS(self, ns_name, qname):
|
130 |
+
element = self._element_stack.pop()
|
131 |
+
el_tag = self._buildTag(ns_name)
|
132 |
+
if el_tag != element.tag:
|
133 |
+
raise SaxError("Unexpected element closed: " + el_tag)
|
134 |
+
|
135 |
+
def startElement(self, name, attributes=None):
|
136 |
+
if attributes:
|
137 |
+
attributes = {(None, k): v for k, v in attributes.items()}
|
138 |
+
self.startElementNS((None, name), name, attributes)
|
139 |
+
|
140 |
+
def endElement(self, name):
|
141 |
+
self.endElementNS((None, name), name)
|
142 |
+
|
143 |
+
def characters(self, data):
|
144 |
+
last_element = self._element_stack[-1]
|
145 |
+
try:
|
146 |
+
# if there already is a child element, we must append to its tail
|
147 |
+
last_element = last_element[-1]
|
148 |
+
last_element.tail = (last_element.tail or '') + data
|
149 |
+
except IndexError:
|
150 |
+
# otherwise: append to the text
|
151 |
+
last_element.text = (last_element.text or '') + data
|
152 |
+
|
153 |
+
ignorableWhitespace = characters
|
154 |
+
|
155 |
+
|
156 |
+
class ElementTreeProducer:
|
157 |
+
"""Produces SAX events for an element and children.
|
158 |
+
"""
|
159 |
+
def __init__(self, element_or_tree, content_handler):
|
160 |
+
try:
|
161 |
+
element = element_or_tree.getroot()
|
162 |
+
except AttributeError:
|
163 |
+
element = element_or_tree
|
164 |
+
self._element = element
|
165 |
+
self._content_handler = content_handler
|
166 |
+
from xml.sax.xmlreader import AttributesNSImpl as attr_class
|
167 |
+
self._attr_class = attr_class
|
168 |
+
self._empty_attributes = attr_class({}, {})
|
169 |
+
|
170 |
+
def saxify(self):
|
171 |
+
self._content_handler.startDocument()
|
172 |
+
|
173 |
+
element = self._element
|
174 |
+
if hasattr(element, 'getprevious'):
|
175 |
+
siblings = []
|
176 |
+
sibling = element.getprevious()
|
177 |
+
while getattr(sibling, 'tag', None) is ProcessingInstruction:
|
178 |
+
siblings.append(sibling)
|
179 |
+
sibling = sibling.getprevious()
|
180 |
+
for sibling in siblings[::-1]:
|
181 |
+
self._recursive_saxify(sibling, {})
|
182 |
+
|
183 |
+
self._recursive_saxify(element, {})
|
184 |
+
|
185 |
+
if hasattr(element, 'getnext'):
|
186 |
+
sibling = element.getnext()
|
187 |
+
while getattr(sibling, 'tag', None) is ProcessingInstruction:
|
188 |
+
self._recursive_saxify(sibling, {})
|
189 |
+
sibling = sibling.getnext()
|
190 |
+
|
191 |
+
self._content_handler.endDocument()
|
192 |
+
|
193 |
+
def _recursive_saxify(self, element, parent_nsmap):
|
194 |
+
content_handler = self._content_handler
|
195 |
+
tag = element.tag
|
196 |
+
if tag is Comment or tag is ProcessingInstruction:
|
197 |
+
if tag is ProcessingInstruction:
|
198 |
+
content_handler.processingInstruction(
|
199 |
+
element.target, element.text)
|
200 |
+
tail = element.tail
|
201 |
+
if tail:
|
202 |
+
content_handler.characters(tail)
|
203 |
+
return
|
204 |
+
|
205 |
+
element_nsmap = element.nsmap
|
206 |
+
new_prefixes = []
|
207 |
+
if element_nsmap != parent_nsmap:
|
208 |
+
# There have been updates to the namespace
|
209 |
+
for prefix, ns_uri in element_nsmap.items():
|
210 |
+
if parent_nsmap.get(prefix) != ns_uri:
|
211 |
+
new_prefixes.append( (prefix, ns_uri) )
|
212 |
+
|
213 |
+
attribs = element.items()
|
214 |
+
if attribs:
|
215 |
+
attr_values = {}
|
216 |
+
attr_qnames = {}
|
217 |
+
for attr_ns_name, value in attribs:
|
218 |
+
attr_ns_tuple = _getNsTag(attr_ns_name)
|
219 |
+
attr_values[attr_ns_tuple] = value
|
220 |
+
attr_qnames[attr_ns_tuple] = self._build_qname(
|
221 |
+
attr_ns_tuple[0], attr_ns_tuple[1], element_nsmap,
|
222 |
+
preferred_prefix=None, is_attribute=True)
|
223 |
+
sax_attributes = self._attr_class(attr_values, attr_qnames)
|
224 |
+
else:
|
225 |
+
sax_attributes = self._empty_attributes
|
226 |
+
|
227 |
+
ns_uri, local_name = _getNsTag(tag)
|
228 |
+
qname = self._build_qname(
|
229 |
+
ns_uri, local_name, element_nsmap, element.prefix, is_attribute=False)
|
230 |
+
|
231 |
+
for prefix, uri in new_prefixes:
|
232 |
+
content_handler.startPrefixMapping(prefix, uri)
|
233 |
+
content_handler.startElementNS(
|
234 |
+
(ns_uri, local_name), qname, sax_attributes)
|
235 |
+
text = element.text
|
236 |
+
if text:
|
237 |
+
content_handler.characters(text)
|
238 |
+
for child in element:
|
239 |
+
self._recursive_saxify(child, element_nsmap)
|
240 |
+
content_handler.endElementNS((ns_uri, local_name), qname)
|
241 |
+
for prefix, uri in new_prefixes:
|
242 |
+
content_handler.endPrefixMapping(prefix)
|
243 |
+
tail = element.tail
|
244 |
+
if tail:
|
245 |
+
content_handler.characters(tail)
|
246 |
+
|
247 |
+
def _build_qname(self, ns_uri, local_name, nsmap, preferred_prefix, is_attribute):
|
248 |
+
if ns_uri is None:
|
249 |
+
return local_name
|
250 |
+
|
251 |
+
if not is_attribute and nsmap.get(preferred_prefix) == ns_uri:
|
252 |
+
prefix = preferred_prefix
|
253 |
+
else:
|
254 |
+
# Pick the first matching prefix, in alphabetical order.
|
255 |
+
candidates = [
|
256 |
+
pfx for (pfx, uri) in nsmap.items()
|
257 |
+
if pfx is not None and uri == ns_uri
|
258 |
+
]
|
259 |
+
prefix = (
|
260 |
+
candidates[0] if len(candidates) == 1
|
261 |
+
else min(candidates) if candidates
|
262 |
+
else None
|
263 |
+
)
|
264 |
+
|
265 |
+
if prefix is None:
|
266 |
+
# Default namespace
|
267 |
+
return local_name
|
268 |
+
return prefix + ':' + local_name
|
269 |
+
|
270 |
+
|
271 |
+
def saxify(element_or_tree, content_handler):
|
272 |
+
"""One-shot helper to generate SAX events from an XML tree and fire
|
273 |
+
them against a SAX ContentHandler.
|
274 |
+
"""
|
275 |
+
return ElementTreeProducer(element_or_tree, content_handler).saxify()
|
llmeval-env/lib/python3.10/site-packages/lxml/schematron.pxi
ADDED
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# support for Schematron validation
|
2 |
+
from lxml.includes cimport schematron
|
3 |
+
|
4 |
+
|
5 |
+
cdef class SchematronError(LxmlError):
|
6 |
+
"""Base class of all Schematron errors.
|
7 |
+
"""
|
8 |
+
|
9 |
+
cdef class SchematronParseError(SchematronError):
|
10 |
+
"""Error while parsing an XML document as Schematron schema.
|
11 |
+
"""
|
12 |
+
|
13 |
+
cdef class SchematronValidateError(SchematronError):
|
14 |
+
"""Error while validating an XML document with a Schematron schema.
|
15 |
+
"""
|
16 |
+
|
17 |
+
|
18 |
+
################################################################################
|
19 |
+
# Schematron
|
20 |
+
|
21 |
+
cdef class Schematron(_Validator):
|
22 |
+
"""Schematron(self, etree=None, file=None)
|
23 |
+
A Schematron validator.
|
24 |
+
|
25 |
+
Pass a root Element or an ElementTree to turn it into a validator.
|
26 |
+
Alternatively, pass a filename as keyword argument 'file' to parse from
|
27 |
+
the file system.
|
28 |
+
|
29 |
+
Schematron is a less well known, but very powerful schema language. The main
|
30 |
+
idea is to use the capabilities of XPath to put restrictions on the structure
|
31 |
+
and the content of XML documents. Here is a simple example::
|
32 |
+
|
33 |
+
>>> schematron = Schematron(XML('''
|
34 |
+
... <schema xmlns="http://www.ascc.net/xml/schematron" >
|
35 |
+
... <pattern name="id is the only permitted attribute name">
|
36 |
+
... <rule context="*">
|
37 |
+
... <report test="@*[not(name()='id')]">Attribute
|
38 |
+
... <name path="@*[not(name()='id')]"/> is forbidden<name/>
|
39 |
+
... </report>
|
40 |
+
... </rule>
|
41 |
+
... </pattern>
|
42 |
+
... </schema>
|
43 |
+
... '''))
|
44 |
+
|
45 |
+
>>> xml = XML('''
|
46 |
+
... <AAA name="aaa">
|
47 |
+
... <BBB id="bbb"/>
|
48 |
+
... <CCC color="ccc"/>
|
49 |
+
... </AAA>
|
50 |
+
... ''')
|
51 |
+
|
52 |
+
>>> schematron.validate(xml)
|
53 |
+
0
|
54 |
+
|
55 |
+
>>> xml = XML('''
|
56 |
+
... <AAA id="aaa">
|
57 |
+
... <BBB id="bbb"/>
|
58 |
+
... <CCC/>
|
59 |
+
... </AAA>
|
60 |
+
... ''')
|
61 |
+
|
62 |
+
>>> schematron.validate(xml)
|
63 |
+
1
|
64 |
+
|
65 |
+
Schematron was added to libxml2 in version 2.6.21. Before version 2.6.32,
|
66 |
+
however, Schematron lacked support for error reporting other than to stderr.
|
67 |
+
This version is therefore required to retrieve validation warnings and
|
68 |
+
errors in lxml.
|
69 |
+
"""
|
70 |
+
cdef schematron.xmlSchematron* _c_schema
|
71 |
+
cdef xmlDoc* _c_schema_doc
|
72 |
+
def __cinit__(self):
|
73 |
+
self._c_schema = NULL
|
74 |
+
self._c_schema_doc = NULL
|
75 |
+
|
76 |
+
def __init__(self, etree=None, *, file=None):
|
77 |
+
cdef _Document doc
|
78 |
+
cdef _Element root_node
|
79 |
+
cdef xmlNode* c_node
|
80 |
+
cdef char* c_href
|
81 |
+
cdef schematron.xmlSchematronParserCtxt* parser_ctxt = NULL
|
82 |
+
_Validator.__init__(self)
|
83 |
+
if not config.ENABLE_SCHEMATRON:
|
84 |
+
raise SchematronError, \
|
85 |
+
"lxml.etree was compiled without Schematron support."
|
86 |
+
if etree is not None:
|
87 |
+
doc = _documentOrRaise(etree)
|
88 |
+
root_node = _rootNodeOrRaise(etree)
|
89 |
+
self._c_schema_doc = _copyDocRoot(doc._c_doc, root_node._c_node)
|
90 |
+
parser_ctxt = schematron.xmlSchematronNewDocParserCtxt(self._c_schema_doc)
|
91 |
+
elif file is not None:
|
92 |
+
filename = _getFilenameForFile(file)
|
93 |
+
if filename is None:
|
94 |
+
# XXX assume a string object
|
95 |
+
filename = file
|
96 |
+
filename = _encodeFilename(filename)
|
97 |
+
with self._error_log:
|
98 |
+
orig_loader = _register_document_loader()
|
99 |
+
parser_ctxt = schematron.xmlSchematronNewParserCtxt(_cstr(filename))
|
100 |
+
_reset_document_loader(orig_loader)
|
101 |
+
else:
|
102 |
+
raise SchematronParseError, "No tree or file given"
|
103 |
+
|
104 |
+
if parser_ctxt is NULL:
|
105 |
+
if self._c_schema_doc is not NULL:
|
106 |
+
tree.xmlFreeDoc(self._c_schema_doc)
|
107 |
+
self._c_schema_doc = NULL
|
108 |
+
raise MemoryError()
|
109 |
+
|
110 |
+
try:
|
111 |
+
with self._error_log:
|
112 |
+
orig_loader = _register_document_loader()
|
113 |
+
self._c_schema = schematron.xmlSchematronParse(parser_ctxt)
|
114 |
+
_reset_document_loader(orig_loader)
|
115 |
+
finally:
|
116 |
+
schematron.xmlSchematronFreeParserCtxt(parser_ctxt)
|
117 |
+
|
118 |
+
if self._c_schema is NULL:
|
119 |
+
raise SchematronParseError(
|
120 |
+
"Document is not a valid Schematron schema",
|
121 |
+
self._error_log)
|
122 |
+
|
123 |
+
def __dealloc__(self):
|
124 |
+
schematron.xmlSchematronFree(self._c_schema)
|
125 |
+
if self._c_schema_doc is not NULL:
|
126 |
+
tree.xmlFreeDoc(self._c_schema_doc)
|
127 |
+
|
128 |
+
def __call__(self, etree):
|
129 |
+
"""__call__(self, etree)
|
130 |
+
|
131 |
+
Validate doc using Schematron.
|
132 |
+
|
133 |
+
Returns true if document is valid, false if not."""
|
134 |
+
cdef _Document doc
|
135 |
+
cdef _Element root_node
|
136 |
+
cdef xmlDoc* c_doc
|
137 |
+
cdef schematron.xmlSchematronValidCtxt* valid_ctxt
|
138 |
+
cdef int ret
|
139 |
+
|
140 |
+
assert self._c_schema is not NULL, "Schematron instance not initialised"
|
141 |
+
doc = _documentOrRaise(etree)
|
142 |
+
root_node = _rootNodeOrRaise(etree)
|
143 |
+
|
144 |
+
valid_ctxt = schematron.xmlSchematronNewValidCtxt(
|
145 |
+
self._c_schema, schematron.XML_SCHEMATRON_OUT_ERROR)
|
146 |
+
if valid_ctxt is NULL:
|
147 |
+
raise MemoryError()
|
148 |
+
|
149 |
+
try:
|
150 |
+
self._error_log.clear()
|
151 |
+
# Need a cast here because older libxml2 releases do not use 'const' in the functype.
|
152 |
+
schematron.xmlSchematronSetValidStructuredErrors(
|
153 |
+
valid_ctxt, <xmlerror.xmlStructuredErrorFunc> _receiveError, <void*>self._error_log)
|
154 |
+
c_doc = _fakeRootDoc(doc._c_doc, root_node._c_node)
|
155 |
+
with nogil:
|
156 |
+
ret = schematron.xmlSchematronValidateDoc(valid_ctxt, c_doc)
|
157 |
+
_destroyFakeDoc(doc._c_doc, c_doc)
|
158 |
+
finally:
|
159 |
+
schematron.xmlSchematronFreeValidCtxt(valid_ctxt)
|
160 |
+
|
161 |
+
if ret == -1:
|
162 |
+
raise SchematronValidateError(
|
163 |
+
"Internal error in Schematron validation",
|
164 |
+
self._error_log)
|
165 |
+
if ret == 0:
|
166 |
+
return True
|
167 |
+
else:
|
168 |
+
return False
|
llmeval-env/lib/python3.10/site-packages/lxml/xinclude.pxi
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# XInclude processing
|
2 |
+
|
3 |
+
from lxml.includes cimport xinclude
|
4 |
+
|
5 |
+
|
6 |
+
cdef class XIncludeError(LxmlError):
|
7 |
+
"""Error during XInclude processing.
|
8 |
+
"""
|
9 |
+
|
10 |
+
|
11 |
+
cdef class XInclude:
|
12 |
+
"""XInclude(self)
|
13 |
+
XInclude processor.
|
14 |
+
|
15 |
+
Create an instance and call it on an Element to run XInclude
|
16 |
+
processing.
|
17 |
+
"""
|
18 |
+
cdef _ErrorLog _error_log
|
19 |
+
def __init__(self):
|
20 |
+
self._error_log = _ErrorLog()
|
21 |
+
|
22 |
+
@property
|
23 |
+
def error_log(self):
|
24 |
+
assert self._error_log is not None, "XInclude instance not initialised"
|
25 |
+
return self._error_log.copy()
|
26 |
+
|
27 |
+
def __call__(self, _Element node not None):
|
28 |
+
"__call__(self, node)"
|
29 |
+
# We cannot pass the XML_PARSE_NOXINCNODE option as this would free
|
30 |
+
# the XInclude nodes - there may still be Python references to them!
|
31 |
+
# Therefore, we allow XInclude nodes to be converted to
|
32 |
+
# XML_XINCLUDE_START nodes. XML_XINCLUDE_END nodes are added as
|
33 |
+
# siblings. Tree traversal will simply ignore them as they are not
|
34 |
+
# typed as elements. The included fragment is added between the two,
|
35 |
+
# i.e. as a sibling, which does not conflict with traversal.
|
36 |
+
cdef int result
|
37 |
+
_assertValidNode(node)
|
38 |
+
assert self._error_log is not None, "XInclude processor not initialised"
|
39 |
+
if node._doc._parser is not None:
|
40 |
+
parse_options = node._doc._parser._parse_options
|
41 |
+
context = node._doc._parser._getParserContext()
|
42 |
+
c_context = <void*>context
|
43 |
+
else:
|
44 |
+
parse_options = 0
|
45 |
+
context = None
|
46 |
+
c_context = NULL
|
47 |
+
|
48 |
+
self._error_log.connect()
|
49 |
+
if tree.LIBXML_VERSION < 20704 or not c_context:
|
50 |
+
__GLOBAL_PARSER_CONTEXT.pushImpliedContext(context)
|
51 |
+
with nogil:
|
52 |
+
orig_loader = _register_document_loader()
|
53 |
+
if c_context:
|
54 |
+
result = xinclude.xmlXIncludeProcessTreeFlagsData(
|
55 |
+
node._c_node, parse_options, c_context)
|
56 |
+
else:
|
57 |
+
result = xinclude.xmlXIncludeProcessTree(node._c_node)
|
58 |
+
_reset_document_loader(orig_loader)
|
59 |
+
if tree.LIBXML_VERSION < 20704 or not c_context:
|
60 |
+
__GLOBAL_PARSER_CONTEXT.popImpliedContext()
|
61 |
+
self._error_log.disconnect()
|
62 |
+
|
63 |
+
if result == -1:
|
64 |
+
raise XIncludeError(
|
65 |
+
self._error_log._buildExceptionMessage(
|
66 |
+
"XInclude processing failed"),
|
67 |
+
self._error_log)
|