blob: c76b14d6a4c2eb4abddcd873eefbc5178b33cbd8 [file] [log] [blame]
Ezio Melottida4b5b82013-01-22 22:47:57 +02001"""Simple implementation of the Level 1 DOM.
2
3Namespaces and other minor Level 2 features are also supported.
Fred Drake55c38192000-06-29 19:39:57 +00004
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +00005parse("foo.xml")
Paul Prescod623511b2000-07-21 22:05:49 +00006
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +00007parseString("<foo><bar/></foo>")
Paul Prescod623511b2000-07-21 22:05:49 +00008
Fred Drake55c38192000-06-29 19:39:57 +00009Todo:
10=====
11 * convenience methods for getting elements and text.
12 * more testing
13 * bring some of the writer and linearizer code into conformance with this
14 interface
15 * SAX 2 namespaces
16"""
17
Guido van Rossum3e1f85e2007-07-27 18:03:11 +000018import io
Thomas Wouters0e3f5912006-08-11 14:57:12 +000019import xml.dom
Fred Drake55c38192000-06-29 19:39:57 +000020
Thomas Wouters0e3f5912006-08-11 14:57:12 +000021from xml.dom import EMPTY_NAMESPACE, EMPTY_PREFIX, XMLNS_NAMESPACE, domreg
22from xml.dom.minicompat import *
23from xml.dom.xmlbuilder import DOMImplementationLS, DocumentLS
Fred Drake3ac6a092001-09-28 04:33:06 +000024
Martin v. Löwis787354c2003-01-25 15:28:29 +000025# This is used by the ID-cache invalidation checks; the list isn't
26# actually complete, since the nodes being checked will never be the
27# DOCUMENT_NODE or DOCUMENT_FRAGMENT_NODE. (The node being checked is
28# the node being added or removed, not the node being modified.)
29#
Thomas Wouters0e3f5912006-08-11 14:57:12 +000030_nodeTypes_with_children = (xml.dom.Node.ELEMENT_NODE,
31 xml.dom.Node.ENTITY_REFERENCE_NODE)
Martin v. Löwis95700f72002-03-15 13:51:59 +000032
Fred Drake3ac6a092001-09-28 04:33:06 +000033
Thomas Wouters0e3f5912006-08-11 14:57:12 +000034class Node(xml.dom.Node):
Martin v. Löwis126f2f62001-03-13 10:50:13 +000035 namespaceURI = None # this is non-null only for elements and attributes
Fred Drake575712e2001-09-28 20:25:45 +000036 parentNode = None
37 ownerDocument = None
Martin v. Löwis787354c2003-01-25 15:28:29 +000038 nextSibling = None
39 previousSibling = None
Martin v. Löwis52ce0d02001-01-27 08:47:37 +000040
Martin v. Löwis787354c2003-01-25 15:28:29 +000041 prefix = EMPTY_PREFIX # non-null only for NS elements and attributes
Fred Drake55c38192000-06-29 19:39:57 +000042
Jack Diederich4dafcc42006-11-28 19:15:13 +000043 def __bool__(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +000044 return True
Fred Drake55c38192000-06-29 19:39:57 +000045
Georg Brandlfe991052009-09-16 15:54:04 +000046 def toxml(self, encoding=None):
Martin v. Löwis7d650ca2002-06-30 15:05:00 +000047 return self.toprettyxml("", "", encoding)
Fred Drake55c38192000-06-29 19:39:57 +000048
Guido van Rossum3e1f85e2007-07-27 18:03:11 +000049 def toprettyxml(self, indent="\t", newl="\n", encoding=None):
Eli Bendersky8a805022012-07-13 09:52:39 +030050 if encoding is None:
51 writer = io.StringIO()
52 else:
53 writer = io.TextIOWrapper(io.BytesIO(),
54 encoding=encoding,
55 errors="xmlcharrefreplace",
56 newline='\n')
Martin v. Löwis7d650ca2002-06-30 15:05:00 +000057 if self.nodeType == Node.DOCUMENT_NODE:
58 # Can pass encoding only to document, to put it into XML header
59 self.writexml(writer, "", indent, newl, encoding)
60 else:
61 self.writexml(writer, "", indent, newl)
Guido van Rossum3e1f85e2007-07-27 18:03:11 +000062 if encoding is None:
Eli Bendersky8a805022012-07-13 09:52:39 +030063 return writer.getvalue()
Guido van Rossum3e1f85e2007-07-27 18:03:11 +000064 else:
Eli Bendersky8a805022012-07-13 09:52:39 +030065 return writer.detach().getvalue()
Martin v. Löwis46fa39a2001-02-06 00:14:08 +000066
Fred Drake1f549022000-09-24 05:21:58 +000067 def hasChildNodes(self):
Florent Xicluna8cf4b512012-03-05 12:37:02 +010068 return bool(self.childNodes)
Martin v. Löwis787354c2003-01-25 15:28:29 +000069
70 def _get_childNodes(self):
71 return self.childNodes
Fred Drake55c38192000-06-29 19:39:57 +000072
Fred Drake1f549022000-09-24 05:21:58 +000073 def _get_firstChild(self):
Fred Drake4ccf4a12000-11-21 22:02:22 +000074 if self.childNodes:
75 return self.childNodes[0]
Paul Prescod73678da2000-07-01 04:58:47 +000076
Fred Drake1f549022000-09-24 05:21:58 +000077 def _get_lastChild(self):
Fred Drake4ccf4a12000-11-21 22:02:22 +000078 if self.childNodes:
79 return self.childNodes[-1]
Paul Prescod73678da2000-07-01 04:58:47 +000080
Fred Drake1f549022000-09-24 05:21:58 +000081 def insertBefore(self, newChild, refChild):
Martin v. Löwis126f2f62001-03-13 10:50:13 +000082 if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE:
Fred Drakee50959a2001-12-06 04:32:18 +000083 for c in tuple(newChild.childNodes):
Martin v. Löwis126f2f62001-03-13 10:50:13 +000084 self.insertBefore(c, refChild)
85 ### The DOM does not clearly specify what to return in this case
86 return newChild
Martin v. Löwis787354c2003-01-25 15:28:29 +000087 if newChild.nodeType not in self._child_node_types:
Thomas Wouters0e3f5912006-08-11 14:57:12 +000088 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +000089 "%s cannot be child of %s" % (repr(newChild), repr(self)))
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +000090 if newChild.parentNode is not None:
91 newChild.parentNode.removeChild(newChild)
Fred Drake4ccf4a12000-11-21 22:02:22 +000092 if refChild is None:
93 self.appendChild(newChild)
94 else:
Martin v. Löwis787354c2003-01-25 15:28:29 +000095 try:
96 index = self.childNodes.index(refChild)
97 except ValueError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +000098 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +000099 if newChild.nodeType in _nodeTypes_with_children:
100 _clear_id_cache(self)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000101 self.childNodes.insert(index, newChild)
102 newChild.nextSibling = refChild
103 refChild.previousSibling = newChild
104 if index:
105 node = self.childNodes[index-1]
106 node.nextSibling = newChild
107 newChild.previousSibling = node
108 else:
109 newChild.previousSibling = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000110 newChild.parentNode = self
Fred Drake4ccf4a12000-11-21 22:02:22 +0000111 return newChild
Fred Drake55c38192000-06-29 19:39:57 +0000112
Fred Drake1f549022000-09-24 05:21:58 +0000113 def appendChild(self, node):
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000114 if node.nodeType == self.DOCUMENT_FRAGMENT_NODE:
Fred Drakee50959a2001-12-06 04:32:18 +0000115 for c in tuple(node.childNodes):
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000116 self.appendChild(c)
117 ### The DOM does not clearly specify what to return in this case
118 return node
Martin v. Löwis787354c2003-01-25 15:28:29 +0000119 if node.nodeType not in self._child_node_types:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000120 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000121 "%s cannot be child of %s" % (repr(node), repr(self)))
122 elif node.nodeType in _nodeTypes_with_children:
123 _clear_id_cache(self)
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +0000124 if node.parentNode is not None:
125 node.parentNode.removeChild(node)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000126 _append_child(self, node)
Fred Drake13a30692000-10-09 20:04:16 +0000127 node.nextSibling = None
Paul Prescod73678da2000-07-01 04:58:47 +0000128 return node
129
Fred Drake1f549022000-09-24 05:21:58 +0000130 def replaceChild(self, newChild, oldChild):
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000131 if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE:
132 refChild = oldChild.nextSibling
133 self.removeChild(oldChild)
134 return self.insertBefore(newChild, refChild)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000135 if newChild.nodeType not in self._child_node_types:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000136 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000137 "%s cannot be child of %s" % (repr(newChild), repr(self)))
Fred Drake4ccf4a12000-11-21 22:02:22 +0000138 if newChild is oldChild:
139 return
Andrew M. Kuchling841d25e2005-11-22 19:03:16 +0000140 if newChild.parentNode is not None:
141 newChild.parentNode.removeChild(newChild)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000142 try:
143 index = self.childNodes.index(oldChild)
144 except ValueError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000145 raise xml.dom.NotFoundErr()
Fred Drake4ccf4a12000-11-21 22:02:22 +0000146 self.childNodes[index] = newChild
Martin v. Löwis787354c2003-01-25 15:28:29 +0000147 newChild.parentNode = self
148 oldChild.parentNode = None
149 if (newChild.nodeType in _nodeTypes_with_children
150 or oldChild.nodeType in _nodeTypes_with_children):
151 _clear_id_cache(self)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000152 newChild.nextSibling = oldChild.nextSibling
153 newChild.previousSibling = oldChild.previousSibling
Martin v. Löwis156c3372000-12-28 18:40:56 +0000154 oldChild.nextSibling = None
Fred Drake4ccf4a12000-11-21 22:02:22 +0000155 oldChild.previousSibling = None
Martin v. Löwis156c3372000-12-28 18:40:56 +0000156 if newChild.previousSibling:
157 newChild.previousSibling.nextSibling = newChild
158 if newChild.nextSibling:
159 newChild.nextSibling.previousSibling = newChild
Fred Drake4ccf4a12000-11-21 22:02:22 +0000160 return oldChild
Paul Prescod73678da2000-07-01 04:58:47 +0000161
Fred Drake1f549022000-09-24 05:21:58 +0000162 def removeChild(self, oldChild):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000163 try:
164 self.childNodes.remove(oldChild)
165 except ValueError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000166 raise xml.dom.NotFoundErr()
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +0000167 if oldChild.nextSibling is not None:
168 oldChild.nextSibling.previousSibling = oldChild.previousSibling
169 if oldChild.previousSibling is not None:
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000170 oldChild.previousSibling.nextSibling = oldChild.nextSibling
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +0000171 oldChild.nextSibling = oldChild.previousSibling = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000172 if oldChild.nodeType in _nodeTypes_with_children:
173 _clear_id_cache(self)
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000174
Martin v. Löwis787354c2003-01-25 15:28:29 +0000175 oldChild.parentNode = None
Fred Drake4ccf4a12000-11-21 22:02:22 +0000176 return oldChild
177
178 def normalize(self):
Fred Drakef7cf40d2000-12-14 18:16:11 +0000179 L = []
180 for child in self.childNodes:
181 if child.nodeType == Node.TEXT_NODE:
R. David Murraydc6da8a2009-04-09 22:16:43 +0000182 if not child.data:
183 # empty text node; discard
184 if L:
185 L[-1].nextSibling = child.nextSibling
186 if child.nextSibling:
187 child.nextSibling.previousSibling = child.previousSibling
188 child.unlink()
189 elif L and L[-1].nodeType == child.nodeType:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000190 # collapse text node
191 node = L[-1]
Martin v. Löwis787354c2003-01-25 15:28:29 +0000192 node.data = node.data + child.data
Fred Drake4ccf4a12000-11-21 22:02:22 +0000193 node.nextSibling = child.nextSibling
R. David Murraydc6da8a2009-04-09 22:16:43 +0000194 if child.nextSibling:
195 child.nextSibling.previousSibling = node
Fred Drake4ccf4a12000-11-21 22:02:22 +0000196 child.unlink()
R. David Murraydc6da8a2009-04-09 22:16:43 +0000197 else:
Fred Drakef7cf40d2000-12-14 18:16:11 +0000198 L.append(child)
Fred Drakef7cf40d2000-12-14 18:16:11 +0000199 else:
Fred Drakef7cf40d2000-12-14 18:16:11 +0000200 L.append(child)
201 if child.nodeType == Node.ELEMENT_NODE:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000202 child.normalize()
Fred Drakef7cf40d2000-12-14 18:16:11 +0000203 self.childNodes[:] = L
Paul Prescod73678da2000-07-01 04:58:47 +0000204
Fred Drake1f549022000-09-24 05:21:58 +0000205 def cloneNode(self, deep):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000206 return _clone_node(self, deep, self.ownerDocument or self)
Fred Drake55c38192000-06-29 19:39:57 +0000207
Martin v. Löwis787354c2003-01-25 15:28:29 +0000208 def isSupported(self, feature, version):
209 return self.ownerDocument.implementation.hasFeature(feature, version)
210
211 def _get_localName(self):
212 # Overridden in Element and Attr where localName can be Non-Null
213 return None
214
215 # Node interfaces from Level 3 (WD 9 April 2002)
Fred Drake25239772001-02-02 19:40:19 +0000216
217 def isSameNode(self, other):
218 return self is other
219
Martin v. Löwis787354c2003-01-25 15:28:29 +0000220 def getInterface(self, feature):
221 if self.isSupported(feature, None):
222 return self
223 else:
224 return None
225
226 # The "user data" functions use a dictionary that is only present
227 # if some user data has been set, so be careful not to assume it
228 # exists.
229
230 def getUserData(self, key):
231 try:
232 return self._user_data[key][0]
233 except (AttributeError, KeyError):
234 return None
235
236 def setUserData(self, key, data, handler):
237 old = None
238 try:
239 d = self._user_data
240 except AttributeError:
241 d = {}
242 self._user_data = d
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000243 if key in d:
Martin v. Löwis787354c2003-01-25 15:28:29 +0000244 old = d[key][0]
245 if data is None:
246 # ignore handlers passed for None
247 handler = None
248 if old is not None:
249 del d[key]
250 else:
251 d[key] = (data, handler)
252 return old
253
254 def _call_user_data_handler(self, operation, src, dst):
255 if hasattr(self, "_user_data"):
Brett Cannon861fd6f2007-02-21 22:05:37 +0000256 for key, (data, handler) in list(self._user_data.items()):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000257 if handler is not None:
258 handler.handle(operation, key, data, src, dst)
259
Fred Drake25239772001-02-02 19:40:19 +0000260 # minidom-specific API:
261
Fred Drake1f549022000-09-24 05:21:58 +0000262 def unlink(self):
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000263 self.parentNode = self.ownerDocument = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000264 if self.childNodes:
265 for child in self.childNodes:
266 child.unlink()
267 self.childNodes = NodeList()
Paul Prescod4221ff02000-10-13 20:11:42 +0000268 self.previousSibling = None
269 self.nextSibling = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000270
Kristján Valur Jónsson17173cf2010-06-09 08:13:42 +0000271 # A Node is its own context manager, to ensure that an unlink() call occurs.
272 # This is similar to how a file object works.
273 def __enter__(self):
274 return self
275
276 def __exit__(self, et, ev, tb):
277 self.unlink()
278
Martin v. Löwis787354c2003-01-25 15:28:29 +0000279defproperty(Node, "firstChild", doc="First child node, or None.")
280defproperty(Node, "lastChild", doc="Last child node, or None.")
281defproperty(Node, "localName", doc="Namespace-local name of this node.")
282
283
284def _append_child(self, node):
285 # fast path with less checks; usable by DOM builders if careful
286 childNodes = self.childNodes
287 if childNodes:
288 last = childNodes[-1]
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100289 node.previousSibling = last
290 last.nextSibling = node
Martin v. Löwis787354c2003-01-25 15:28:29 +0000291 childNodes.append(node)
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100292 node.parentNode = self
Martin v. Löwis787354c2003-01-25 15:28:29 +0000293
294def _in_document(node):
295 # return True iff node is part of a document tree
296 while node is not None:
297 if node.nodeType == Node.DOCUMENT_NODE:
298 return True
299 node = node.parentNode
300 return False
Fred Drake55c38192000-06-29 19:39:57 +0000301
Fred Drake1f549022000-09-24 05:21:58 +0000302def _write_data(writer, data):
Fred Drake55c38192000-06-29 19:39:57 +0000303 "Writes datachars to writer."
Georg Brandlb9cd72a2010-10-15 17:58:45 +0000304 if data:
305 data = data.replace("&", "&amp;").replace("<", "&lt;"). \
306 replace("\"", "&quot;").replace(">", "&gt;")
307 writer.write(data)
Fred Drake55c38192000-06-29 19:39:57 +0000308
Martin v. Löwis787354c2003-01-25 15:28:29 +0000309def _get_elements_by_tagName_helper(parent, name, rc):
Fred Drake55c38192000-06-29 19:39:57 +0000310 for node in parent.childNodes:
Fred Drake1f549022000-09-24 05:21:58 +0000311 if node.nodeType == Node.ELEMENT_NODE and \
312 (name == "*" or node.tagName == name):
313 rc.append(node)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000314 _get_elements_by_tagName_helper(node, name, rc)
Fred Drake55c38192000-06-29 19:39:57 +0000315 return rc
316
Martin v. Löwis787354c2003-01-25 15:28:29 +0000317def _get_elements_by_tagName_ns_helper(parent, nsURI, localName, rc):
Fred Drake55c38192000-06-29 19:39:57 +0000318 for node in parent.childNodes:
Fred Drake1f549022000-09-24 05:21:58 +0000319 if node.nodeType == Node.ELEMENT_NODE:
Martin v. Löwised525fb2001-06-03 14:06:42 +0000320 if ((localName == "*" or node.localName == localName) and
Fred Drake1f549022000-09-24 05:21:58 +0000321 (nsURI == "*" or node.namespaceURI == nsURI)):
322 rc.append(node)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000323 _get_elements_by_tagName_ns_helper(node, nsURI, localName, rc)
Fred Drakef7cf40d2000-12-14 18:16:11 +0000324 return rc
Fred Drake55c38192000-06-29 19:39:57 +0000325
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000326class DocumentFragment(Node):
327 nodeType = Node.DOCUMENT_FRAGMENT_NODE
328 nodeName = "#document-fragment"
329 nodeValue = None
330 attributes = None
331 parentNode = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000332 _child_node_types = (Node.ELEMENT_NODE,
333 Node.TEXT_NODE,
334 Node.CDATA_SECTION_NODE,
335 Node.ENTITY_REFERENCE_NODE,
336 Node.PROCESSING_INSTRUCTION_NODE,
337 Node.COMMENT_NODE,
338 Node.NOTATION_NODE)
339
340 def __init__(self):
341 self.childNodes = NodeList()
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000342
343
Fred Drake55c38192000-06-29 19:39:57 +0000344class Attr(Node):
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100345 __slots__=('_name', '_value', 'namespaceURI',
346 '_prefix', 'childNodes', '_localName', 'ownerDocument', 'ownerElement')
Fred Drake1f549022000-09-24 05:21:58 +0000347 nodeType = Node.ATTRIBUTE_NODE
Fred Drake4ccf4a12000-11-21 22:02:22 +0000348 attributes = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000349 specified = False
350 _is_id = False
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000351
Martin v. Löwis787354c2003-01-25 15:28:29 +0000352 _child_node_types = (Node.TEXT_NODE, Node.ENTITY_REFERENCE_NODE)
353
354 def __init__(self, qName, namespaceURI=EMPTY_NAMESPACE, localName=None,
355 prefix=None):
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100356 self.ownerElement = None
357 self._name = qName
358 self.namespaceURI = namespaceURI
359 self._prefix = prefix
360 self.childNodes = NodeList()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000361
362 # Add the single child node that represents the value of the attr
363 self.childNodes.append(Text())
364
Paul Prescod73678da2000-07-01 04:58:47 +0000365 # nodeValue and value are set elsewhere
Fred Drake55c38192000-06-29 19:39:57 +0000366
Martin v. Löwis787354c2003-01-25 15:28:29 +0000367 def _get_localName(self):
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100368 try:
369 return self._localName
370 except AttributeError:
371 return self.nodeName.split(":", 1)[-1]
Martin v. Löwis787354c2003-01-25 15:28:29 +0000372
Martin v. Löwis787354c2003-01-25 15:28:29 +0000373 def _get_specified(self):
374 return self.specified
375
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100376 def _get_name(self):
377 return self._name
378
379 def _set_name(self, value):
380 self._name = value
381 if self.ownerElement is not None:
382 _clear_id_cache(self.ownerElement)
383
384 nodeName = name = property(_get_name, _set_name)
385
386 def _get_value(self):
387 return self._value
388
389 def _set_value(self, value):
390 self._value = value
391 self.childNodes[0].data = value
392 if self.ownerElement is not None:
393 _clear_id_cache(self.ownerElement)
394 self.childNodes[0].data = value
395
396 nodeValue = value = property(_get_value, _set_value)
397
398 def _get_prefix(self):
399 return self._prefix
Fred Drake55c38192000-06-29 19:39:57 +0000400
Martin v. Löwis995359c2003-01-26 08:59:32 +0000401 def _set_prefix(self, prefix):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000402 nsuri = self.namespaceURI
Martin v. Löwis995359c2003-01-26 08:59:32 +0000403 if prefix == "xmlns":
404 if nsuri and nsuri != XMLNS_NAMESPACE:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000405 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000406 "illegal use of 'xmlns' prefix for the wrong namespace")
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100407 self._prefix = prefix
Martin v. Löwis787354c2003-01-25 15:28:29 +0000408 if prefix is None:
409 newName = self.localName
410 else:
Martin v. Löwis995359c2003-01-26 08:59:32 +0000411 newName = "%s:%s" % (prefix, self.localName)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000412 if self.ownerElement:
413 _clear_id_cache(self.ownerElement)
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100414 self.name = newName
Martin v. Löwis787354c2003-01-25 15:28:29 +0000415
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100416 prefix = property(_get_prefix, _set_prefix)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000417
418 def unlink(self):
419 # This implementation does not call the base implementation
420 # since most of that is not needed, and the expense of the
421 # method call is not warranted. We duplicate the removal of
422 # children, but that's all we needed from the base class.
423 elem = self.ownerElement
424 if elem is not None:
425 del elem._attrs[self.nodeName]
426 del elem._attrsNS[(self.namespaceURI, self.localName)]
427 if self._is_id:
428 self._is_id = False
429 elem._magic_id_nodes -= 1
430 self.ownerDocument._magic_id_count -= 1
431 for child in self.childNodes:
432 child.unlink()
433 del self.childNodes[:]
434
435 def _get_isId(self):
436 if self._is_id:
437 return True
438 doc = self.ownerDocument
439 elem = self.ownerElement
440 if doc is None or elem is None:
441 return False
442
443 info = doc._get_elem_info(elem)
444 if info is None:
445 return False
446 if self.namespaceURI:
447 return info.isIdNS(self.namespaceURI, self.localName)
448 else:
449 return info.isId(self.nodeName)
450
451 def _get_schemaType(self):
452 doc = self.ownerDocument
453 elem = self.ownerElement
454 if doc is None or elem is None:
455 return _no_type
456
457 info = doc._get_elem_info(elem)
458 if info is None:
459 return _no_type
460 if self.namespaceURI:
461 return info.getAttributeTypeNS(self.namespaceURI, self.localName)
462 else:
463 return info.getAttributeType(self.nodeName)
464
465defproperty(Attr, "isId", doc="True if this attribute is an ID.")
466defproperty(Attr, "localName", doc="Namespace-local name of this attribute.")
467defproperty(Attr, "schemaType", doc="Schema type for this attribute.")
Fred Drake4ccf4a12000-11-21 22:02:22 +0000468
Fred Drakef7cf40d2000-12-14 18:16:11 +0000469
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000470class NamedNodeMap(object):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000471 """The attribute list is a transient interface to the underlying
472 dictionaries. Mutations here will change the underlying element's
Fred Drakef7cf40d2000-12-14 18:16:11 +0000473 dictionary.
474
475 Ordering is imposed artificially and does not reflect the order of
476 attributes as found in an input document.
477 """
Fred Drake4ccf4a12000-11-21 22:02:22 +0000478
Martin v. Löwis787354c2003-01-25 15:28:29 +0000479 __slots__ = ('_attrs', '_attrsNS', '_ownerElement')
480
Fred Drake2998a552001-12-06 18:27:48 +0000481 def __init__(self, attrs, attrsNS, ownerElement):
Fred Drake1f549022000-09-24 05:21:58 +0000482 self._attrs = attrs
483 self._attrsNS = attrsNS
Fred Drake2998a552001-12-06 18:27:48 +0000484 self._ownerElement = ownerElement
Fred Drakef7cf40d2000-12-14 18:16:11 +0000485
Martin v. Löwis787354c2003-01-25 15:28:29 +0000486 def _get_length(self):
487 return len(self._attrs)
Fred Drake55c38192000-06-29 19:39:57 +0000488
Fred Drake1f549022000-09-24 05:21:58 +0000489 def item(self, index):
Fred Drake55c38192000-06-29 19:39:57 +0000490 try:
Brett Cannon861fd6f2007-02-21 22:05:37 +0000491 return self[list(self._attrs.keys())[index]]
Fred Drake55c38192000-06-29 19:39:57 +0000492 except IndexError:
493 return None
Fred Drake55c38192000-06-29 19:39:57 +0000494
Fred Drake1f549022000-09-24 05:21:58 +0000495 def items(self):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000496 L = []
497 for node in self._attrs.values():
Martin v. Löwisd5fb58f2001-01-27 08:38:34 +0000498 L.append((node.nodeName, node.value))
Fred Drake4ccf4a12000-11-21 22:02:22 +0000499 return L
Fred Drake1f549022000-09-24 05:21:58 +0000500
501 def itemsNS(self):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000502 L = []
503 for node in self._attrs.values():
Fred Drake49a5d032001-11-30 22:21:58 +0000504 L.append(((node.namespaceURI, node.localName), node.value))
Fred Drake4ccf4a12000-11-21 22:02:22 +0000505 return L
Fred Drake16f63292000-10-23 18:09:50 +0000506
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000507 def __contains__(self, key):
Christian Heimesc9543e42007-11-28 08:28:28 +0000508 if isinstance(key, str):
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000509 return key in self._attrs
Martin v. Löwis787354c2003-01-25 15:28:29 +0000510 else:
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000511 return key in self._attrsNS
Martin v. Löwis787354c2003-01-25 15:28:29 +0000512
Fred Drake1f549022000-09-24 05:21:58 +0000513 def keys(self):
Paul Prescod73678da2000-07-01 04:58:47 +0000514 return self._attrs.keys()
Fred Drake55c38192000-06-29 19:39:57 +0000515
Fred Drake1f549022000-09-24 05:21:58 +0000516 def keysNS(self):
Paul Prescod73678da2000-07-01 04:58:47 +0000517 return self._attrsNS.keys()
Fred Drake55c38192000-06-29 19:39:57 +0000518
Fred Drake1f549022000-09-24 05:21:58 +0000519 def values(self):
Paul Prescod73678da2000-07-01 04:58:47 +0000520 return self._attrs.values()
Fred Drake55c38192000-06-29 19:39:57 +0000521
Martin v. Löwis787354c2003-01-25 15:28:29 +0000522 def get(self, name, value=None):
Martin v. Löwisd5fb58f2001-01-27 08:38:34 +0000523 return self._attrs.get(name, value)
524
Martin v. Löwis787354c2003-01-25 15:28:29 +0000525 __len__ = _get_length
Fred Drake55c38192000-06-29 19:39:57 +0000526
Mark Dickinsona56c4672009-01-27 18:17:45 +0000527 def _cmp(self, other):
Fred Drake1f549022000-09-24 05:21:58 +0000528 if self._attrs is getattr(other, "_attrs", None):
Fred Drake55c38192000-06-29 19:39:57 +0000529 return 0
Fred Drake16f63292000-10-23 18:09:50 +0000530 else:
Mark Dickinsona56c4672009-01-27 18:17:45 +0000531 return (id(self) > id(other)) - (id(self) < id(other))
532
533 def __eq__(self, other):
534 return self._cmp(other) == 0
535
536 def __ge__(self, other):
537 return self._cmp(other) >= 0
538
539 def __gt__(self, other):
540 return self._cmp(other) > 0
541
542 def __le__(self, other):
543 return self._cmp(other) <= 0
544
545 def __lt__(self, other):
546 return self._cmp(other) < 0
547
548 def __ne__(self, other):
549 return self._cmp(other) != 0
Fred Drake55c38192000-06-29 19:39:57 +0000550
Fred Drake1f549022000-09-24 05:21:58 +0000551 def __getitem__(self, attname_or_tuple):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000552 if isinstance(attname_or_tuple, tuple):
Paul Prescod73678da2000-07-01 04:58:47 +0000553 return self._attrsNS[attname_or_tuple]
Fred Drake55c38192000-06-29 19:39:57 +0000554 else:
Paul Prescod73678da2000-07-01 04:58:47 +0000555 return self._attrs[attname_or_tuple]
Fred Drake55c38192000-06-29 19:39:57 +0000556
Paul Prescod1e688272000-07-01 19:21:47 +0000557 # same as set
Fred Drake1f549022000-09-24 05:21:58 +0000558 def __setitem__(self, attname, value):
Christian Heimesc9543e42007-11-28 08:28:28 +0000559 if isinstance(value, str):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000560 try:
561 node = self._attrs[attname]
562 except KeyError:
563 node = Attr(attname)
564 node.ownerDocument = self._ownerElement.ownerDocument
Martin v. Löwis995359c2003-01-26 08:59:32 +0000565 self.setNamedItem(node)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000566 node.value = value
Paul Prescod1e688272000-07-01 19:21:47 +0000567 else:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000568 if not isinstance(value, Attr):
Collin Winter70e79802007-08-24 18:57:22 +0000569 raise TypeError("value must be a string or Attr object")
Fred Drake1f549022000-09-24 05:21:58 +0000570 node = value
Martin v. Löwis787354c2003-01-25 15:28:29 +0000571 self.setNamedItem(node)
572
573 def getNamedItem(self, name):
574 try:
575 return self._attrs[name]
576 except KeyError:
577 return None
578
579 def getNamedItemNS(self, namespaceURI, localName):
580 try:
581 return self._attrsNS[(namespaceURI, localName)]
582 except KeyError:
583 return None
584
585 def removeNamedItem(self, name):
586 n = self.getNamedItem(name)
587 if n is not None:
588 _clear_id_cache(self._ownerElement)
589 del self._attrs[n.nodeName]
590 del self._attrsNS[(n.namespaceURI, n.localName)]
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100591 if hasattr(n, 'ownerElement'):
592 n.ownerElement = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000593 return n
594 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000595 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000596
597 def removeNamedItemNS(self, namespaceURI, localName):
598 n = self.getNamedItemNS(namespaceURI, localName)
599 if n is not None:
600 _clear_id_cache(self._ownerElement)
601 del self._attrsNS[(n.namespaceURI, n.localName)]
602 del self._attrs[n.nodeName]
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100603 if hasattr(n, 'ownerElement'):
604 n.ownerElement = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000605 return n
606 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000607 raise xml.dom.NotFoundErr()
Fred Drakef7cf40d2000-12-14 18:16:11 +0000608
609 def setNamedItem(self, node):
Andrew M. Kuchlingbc8f72c2001-02-21 01:30:26 +0000610 if not isinstance(node, Attr):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000611 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000612 "%s cannot be child of %s" % (repr(node), repr(self)))
Fred Drakef7cf40d2000-12-14 18:16:11 +0000613 old = self._attrs.get(node.name)
Paul Prescod1e688272000-07-01 19:21:47 +0000614 if old:
615 old.unlink()
Fred Drake1f549022000-09-24 05:21:58 +0000616 self._attrs[node.name] = node
617 self._attrsNS[(node.namespaceURI, node.localName)] = node
Fred Drake2998a552001-12-06 18:27:48 +0000618 node.ownerElement = self._ownerElement
Martin v. Löwis787354c2003-01-25 15:28:29 +0000619 _clear_id_cache(node.ownerElement)
Fred Drakef7cf40d2000-12-14 18:16:11 +0000620 return old
621
622 def setNamedItemNS(self, node):
623 return self.setNamedItem(node)
Paul Prescod73678da2000-07-01 04:58:47 +0000624
Fred Drake1f549022000-09-24 05:21:58 +0000625 def __delitem__(self, attname_or_tuple):
626 node = self[attname_or_tuple]
Martin v. Löwis787354c2003-01-25 15:28:29 +0000627 _clear_id_cache(node.ownerElement)
Paul Prescod73678da2000-07-01 04:58:47 +0000628 node.unlink()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000629
630 def __getstate__(self):
631 return self._attrs, self._attrsNS, self._ownerElement
632
633 def __setstate__(self, state):
634 self._attrs, self._attrsNS, self._ownerElement = state
635
636defproperty(NamedNodeMap, "length",
637 doc="Number of nodes in the NamedNodeMap.")
Fred Drakef7cf40d2000-12-14 18:16:11 +0000638
639AttributeList = NamedNodeMap
640
Fred Drake1f549022000-09-24 05:21:58 +0000641
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000642class TypeInfo(object):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000643 __slots__ = 'namespace', 'name'
644
645 def __init__(self, namespace, name):
646 self.namespace = namespace
647 self.name = name
648
649 def __repr__(self):
650 if self.namespace:
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300651 return "<%s %r (from %r)>" % (self.__class__.__name__, self.name,
652 self.namespace)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000653 else:
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300654 return "<%s %r>" % (self.__class__.__name__, self.name)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000655
656 def _get_name(self):
657 return self.name
658
659 def _get_namespace(self):
660 return self.namespace
661
662_no_type = TypeInfo(None, None)
663
Martin v. Löwisa2fda0d2000-10-07 12:10:28 +0000664class Element(Node):
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100665 __slots__=('ownerDocument', 'parentNode', 'tagName', 'nodeName', 'prefix',
666 'namespaceURI', '_localName', 'childNodes', '_attrs', '_attrsNS',
667 'nextSibling', 'previousSibling')
Fred Drake1f549022000-09-24 05:21:58 +0000668 nodeType = Node.ELEMENT_NODE
Martin v. Löwis787354c2003-01-25 15:28:29 +0000669 nodeValue = None
670 schemaType = _no_type
671
672 _magic_id_nodes = 0
673
674 _child_node_types = (Node.ELEMENT_NODE,
675 Node.PROCESSING_INSTRUCTION_NODE,
676 Node.COMMENT_NODE,
677 Node.TEXT_NODE,
678 Node.CDATA_SECTION_NODE,
679 Node.ENTITY_REFERENCE_NODE)
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000680
Fred Drake49a5d032001-11-30 22:21:58 +0000681 def __init__(self, tagName, namespaceURI=EMPTY_NAMESPACE, prefix=None,
Fred Drake1f549022000-09-24 05:21:58 +0000682 localName=None):
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100683 self.parentNode = None
Fred Drake55c38192000-06-29 19:39:57 +0000684 self.tagName = self.nodeName = tagName
Fred Drake1f549022000-09-24 05:21:58 +0000685 self.prefix = prefix
686 self.namespaceURI = namespaceURI
Martin v. Löwis787354c2003-01-25 15:28:29 +0000687 self.childNodes = NodeList()
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100688 self.nextSibling = self.previousSibling = None
Fred Drake55c38192000-06-29 19:39:57 +0000689
Martin v. Löwis7b771882012-02-19 20:55:05 +0100690 # Attribute dictionaries are lazily created
691 # attributes are double-indexed:
692 # tagName -> Attribute
693 # URI,localName -> Attribute
694 # in the future: consider lazy generation
695 # of attribute objects this is too tricky
696 # for now because of headaches with
697 # namespaces.
698 self._attrs = None
699 self._attrsNS = None
700
701 def _ensure_attributes(self):
702 if self._attrs is None:
703 self._attrs = {}
704 self._attrsNS = {}
Fred Drake4ccf4a12000-11-21 22:02:22 +0000705
Martin v. Löwis787354c2003-01-25 15:28:29 +0000706 def _get_localName(self):
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100707 try:
708 return self._localName
709 except AttributeError:
710 return self.tagName.split(":", 1)[-1]
Martin v. Löwis787354c2003-01-25 15:28:29 +0000711
712 def _get_tagName(self):
713 return self.tagName
Fred Drake4ccf4a12000-11-21 22:02:22 +0000714
715 def unlink(self):
Martin v. Löwis7b771882012-02-19 20:55:05 +0100716 if self._attrs is not None:
717 for attr in list(self._attrs.values()):
718 attr.unlink()
Fred Drake4ccf4a12000-11-21 22:02:22 +0000719 self._attrs = None
720 self._attrsNS = None
721 Node.unlink(self)
Fred Drake55c38192000-06-29 19:39:57 +0000722
Fred Drake1f549022000-09-24 05:21:58 +0000723 def getAttribute(self, attname):
Martin v. Löwis67245a62012-03-05 07:01:49 +0100724 if self._attrs is None:
725 return ""
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000726 try:
727 return self._attrs[attname].value
728 except KeyError:
729 return ""
Fred Drake55c38192000-06-29 19:39:57 +0000730
Fred Drake1f549022000-09-24 05:21:58 +0000731 def getAttributeNS(self, namespaceURI, localName):
Martin v. Löwis67245a62012-03-05 07:01:49 +0100732 if self._attrsNS is None:
733 return ""
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000734 try:
735 return self._attrsNS[(namespaceURI, localName)].value
736 except KeyError:
737 return ""
Fred Drake1f549022000-09-24 05:21:58 +0000738
739 def setAttribute(self, attname, value):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000740 attr = self.getAttributeNode(attname)
741 if attr is None:
742 attr = Attr(attname)
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100743 attr.value = value # also sets nodeValue
744 attr.ownerDocument = self.ownerDocument
Martin v. Löwis787354c2003-01-25 15:28:29 +0000745 self.setAttributeNode(attr)
746 elif value != attr.value:
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100747 attr.value = value
Martin v. Löwis787354c2003-01-25 15:28:29 +0000748 if attr.isId:
749 _clear_id_cache(self)
Fred Drake55c38192000-06-29 19:39:57 +0000750
Fred Drake1f549022000-09-24 05:21:58 +0000751 def setAttributeNS(self, namespaceURI, qualifiedName, value):
752 prefix, localname = _nssplit(qualifiedName)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000753 attr = self.getAttributeNodeNS(namespaceURI, localname)
754 if attr is None:
Martin v. Löwis787354c2003-01-25 15:28:29 +0000755 attr = Attr(qualifiedName, namespaceURI, localname, prefix)
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100756 attr.value = value
757 attr.ownerDocument = self.ownerDocument
Martin v. Löwis787354c2003-01-25 15:28:29 +0000758 self.setAttributeNode(attr)
759 else:
Martin v. Löwis787354c2003-01-25 15:28:29 +0000760 if value != attr.value:
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100761 attr.value = value
Martin v. Löwis787354c2003-01-25 15:28:29 +0000762 if attr.isId:
763 _clear_id_cache(self)
764 if attr.prefix != prefix:
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100765 attr.prefix = prefix
766 attr.nodeName = qualifiedName
Fred Drake55c38192000-06-29 19:39:57 +0000767
Fred Drake1f549022000-09-24 05:21:58 +0000768 def getAttributeNode(self, attrname):
Martin v. Löwis7b771882012-02-19 20:55:05 +0100769 if self._attrs is None:
770 return None
Fred Drake1f549022000-09-24 05:21:58 +0000771 return self._attrs.get(attrname)
Paul Prescod73678da2000-07-01 04:58:47 +0000772
Fred Drake1f549022000-09-24 05:21:58 +0000773 def getAttributeNodeNS(self, namespaceURI, localName):
Martin v. Löwis7b771882012-02-19 20:55:05 +0100774 if self._attrsNS is None:
775 return None
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000776 return self._attrsNS.get((namespaceURI, localName))
Paul Prescod73678da2000-07-01 04:58:47 +0000777
Fred Drake1f549022000-09-24 05:21:58 +0000778 def setAttributeNode(self, attr):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000779 if attr.ownerElement not in (None, self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000780 raise xml.dom.InuseAttributeErr("attribute node already owned")
Martin v. Löwis7b771882012-02-19 20:55:05 +0100781 self._ensure_attributes()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000782 old1 = self._attrs.get(attr.name, None)
783 if old1 is not None:
784 self.removeAttributeNode(old1)
785 old2 = self._attrsNS.get((attr.namespaceURI, attr.localName), None)
786 if old2 is not None and old2 is not old1:
787 self.removeAttributeNode(old2)
788 _set_attribute_node(self, attr)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000789
Martin v. Löwis787354c2003-01-25 15:28:29 +0000790 if old1 is not attr:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000791 # It might have already been part of this node, in which case
792 # it doesn't represent a change, and should not be returned.
Martin v. Löwis787354c2003-01-25 15:28:29 +0000793 return old1
794 if old2 is not attr:
795 return old2
Fred Drake55c38192000-06-29 19:39:57 +0000796
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000797 setAttributeNodeNS = setAttributeNode
798
Fred Drake1f549022000-09-24 05:21:58 +0000799 def removeAttribute(self, name):
Martin v. Löwis7b771882012-02-19 20:55:05 +0100800 if self._attrsNS is None:
801 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000802 try:
803 attr = self._attrs[name]
804 except KeyError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000805 raise xml.dom.NotFoundErr()
Fred Drake1f549022000-09-24 05:21:58 +0000806 self.removeAttributeNode(attr)
Fred Drake55c38192000-06-29 19:39:57 +0000807
Fred Drake1f549022000-09-24 05:21:58 +0000808 def removeAttributeNS(self, namespaceURI, localName):
Martin v. Löwis7b771882012-02-19 20:55:05 +0100809 if self._attrsNS is None:
810 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000811 try:
812 attr = self._attrsNS[(namespaceURI, localName)]
813 except KeyError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000814 raise xml.dom.NotFoundErr()
Fred Drake1f549022000-09-24 05:21:58 +0000815 self.removeAttributeNode(attr)
Fred Drake55c38192000-06-29 19:39:57 +0000816
Fred Drake1f549022000-09-24 05:21:58 +0000817 def removeAttributeNode(self, node):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000818 if node is None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000819 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000820 try:
821 self._attrs[node.name]
822 except KeyError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000823 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000824 _clear_id_cache(self)
Paul Prescod73678da2000-07-01 04:58:47 +0000825 node.unlink()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000826 # Restore this since the node is still useful and otherwise
827 # unlinked
828 node.ownerDocument = self.ownerDocument
Fred Drake16f63292000-10-23 18:09:50 +0000829
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000830 removeAttributeNodeNS = removeAttributeNode
831
Martin v. Löwis156c3372000-12-28 18:40:56 +0000832 def hasAttribute(self, name):
Martin v. Löwis7b771882012-02-19 20:55:05 +0100833 if self._attrs is None:
834 return False
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000835 return name in self._attrs
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000836
Martin v. Löwis156c3372000-12-28 18:40:56 +0000837 def hasAttributeNS(self, namespaceURI, localName):
Martin v. Löwis7b771882012-02-19 20:55:05 +0100838 if self._attrsNS is None:
839 return False
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000840 return (namespaceURI, localName) in self._attrsNS
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000841
Fred Drake1f549022000-09-24 05:21:58 +0000842 def getElementsByTagName(self, name):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000843 return _get_elements_by_tagName_helper(self, name, NodeList())
Fred Drake55c38192000-06-29 19:39:57 +0000844
Fred Drake1f549022000-09-24 05:21:58 +0000845 def getElementsByTagNameNS(self, namespaceURI, localName):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000846 return _get_elements_by_tagName_ns_helper(
847 self, namespaceURI, localName, NodeList())
Fred Drake55c38192000-06-29 19:39:57 +0000848
Fred Drake1f549022000-09-24 05:21:58 +0000849 def __repr__(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000850 return "<DOM Element: %s at %#x>" % (self.tagName, id(self))
Fred Drake55c38192000-06-29 19:39:57 +0000851
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000852 def writexml(self, writer, indent="", addindent="", newl=""):
853 # indent = current indentation
854 # addindent = indentation to add to higher levels
855 # newl = newline string
856 writer.write(indent+"<" + self.tagName)
Fred Drake16f63292000-10-23 18:09:50 +0000857
Fred Drake4ccf4a12000-11-21 22:02:22 +0000858 attrs = self._get_attributes()
Brett Cannon861fd6f2007-02-21 22:05:37 +0000859 a_names = sorted(attrs.keys())
Fred Drake55c38192000-06-29 19:39:57 +0000860
861 for a_name in a_names:
Fred Drake1f549022000-09-24 05:21:58 +0000862 writer.write(" %s=\"" % a_name)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000863 _write_data(writer, attrs[a_name].value)
Fred Drake55c38192000-06-29 19:39:57 +0000864 writer.write("\"")
865 if self.childNodes:
R David Murray791744b2011-10-01 16:19:51 -0400866 writer.write(">")
Ezio Melotti8008f2a2011-11-18 17:34:26 +0200867 if (len(self.childNodes) == 1 and
868 self.childNodes[0].nodeType == Node.TEXT_NODE):
869 self.childNodes[0].writexml(writer, '', '', '')
870 else:
R David Murray791744b2011-10-01 16:19:51 -0400871 writer.write(newl)
Ezio Melotti8008f2a2011-11-18 17:34:26 +0200872 for node in self.childNodes:
873 node.writexml(writer, indent+addindent, addindent, newl)
874 writer.write(indent)
875 writer.write("</%s>%s" % (self.tagName, newl))
Fred Drake55c38192000-06-29 19:39:57 +0000876 else:
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000877 writer.write("/>%s"%(newl))
Fred Drake55c38192000-06-29 19:39:57 +0000878
Fred Drake1f549022000-09-24 05:21:58 +0000879 def _get_attributes(self):
Martin v. Löwis7b771882012-02-19 20:55:05 +0100880 self._ensure_attributes()
Fred Drake2998a552001-12-06 18:27:48 +0000881 return NamedNodeMap(self._attrs, self._attrsNS, self)
Fred Drake55c38192000-06-29 19:39:57 +0000882
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000883 def hasAttributes(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000884 if self._attrs:
885 return True
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000886 else:
Martin v. Löwis787354c2003-01-25 15:28:29 +0000887 return False
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000888
Martin v. Löwis787354c2003-01-25 15:28:29 +0000889 # DOM Level 3 attributes, based on the 22 Oct 2002 draft
890
891 def setIdAttribute(self, name):
892 idAttr = self.getAttributeNode(name)
893 self.setIdAttributeNode(idAttr)
894
895 def setIdAttributeNS(self, namespaceURI, localName):
896 idAttr = self.getAttributeNodeNS(namespaceURI, localName)
897 self.setIdAttributeNode(idAttr)
898
899 def setIdAttributeNode(self, idAttr):
900 if idAttr is None or not self.isSameNode(idAttr.ownerElement):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000901 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000902 if _get_containing_entref(self) is not None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000903 raise xml.dom.NoModificationAllowedErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000904 if not idAttr._is_id:
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100905 idAttr._is_id = True
Martin v. Löwis787354c2003-01-25 15:28:29 +0000906 self._magic_id_nodes += 1
907 self.ownerDocument._magic_id_count += 1
908 _clear_id_cache(self)
909
910defproperty(Element, "attributes",
911 doc="NamedNodeMap of attributes on the element.")
912defproperty(Element, "localName",
913 doc="Namespace-local name of this element.")
914
915
916def _set_attribute_node(element, attr):
917 _clear_id_cache(element)
Martin v. Löwis7b771882012-02-19 20:55:05 +0100918 element._ensure_attributes()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000919 element._attrs[attr.name] = attr
920 element._attrsNS[(attr.namespaceURI, attr.localName)] = attr
921
922 # This creates a circular reference, but Element.unlink()
923 # breaks the cycle since the references to the attribute
924 # dictionaries are tossed.
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100925 attr.ownerElement = element
Martin v. Löwis787354c2003-01-25 15:28:29 +0000926
927class Childless:
928 """Mixin that makes childless-ness easy to implement and avoids
929 the complexity of the Node methods that deal with children.
930 """
Florent Xicluna8cf4b512012-03-05 12:37:02 +0100931 __slots__ = ()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000932
Fred Drake4ccf4a12000-11-21 22:02:22 +0000933 attributes = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000934 childNodes = EmptyNodeList()
935 firstChild = None
936 lastChild = None
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000937
Martin v. Löwis787354c2003-01-25 15:28:29 +0000938 def _get_firstChild(self):
939 return None
Fred Drake55c38192000-06-29 19:39:57 +0000940
Martin v. Löwis787354c2003-01-25 15:28:29 +0000941 def _get_lastChild(self):
942 return None
Fred Drake1f549022000-09-24 05:21:58 +0000943
Martin v. Löwis787354c2003-01-25 15:28:29 +0000944 def appendChild(self, node):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000945 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000946 self.nodeName + " nodes cannot have children")
947
948 def hasChildNodes(self):
949 return False
950
951 def insertBefore(self, newChild, refChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000952 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000953 self.nodeName + " nodes do not have children")
954
955 def removeChild(self, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000956 raise xml.dom.NotFoundErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000957 self.nodeName + " nodes do not have children")
958
Andrew M. Kuchling688b9e32010-07-25 23:38:47 +0000959 def normalize(self):
960 # For childless nodes, normalize() has nothing to do.
961 pass
962
Martin v. Löwis787354c2003-01-25 15:28:29 +0000963 def replaceChild(self, newChild, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000964 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000965 self.nodeName + " nodes do not have children")
966
967
968class ProcessingInstruction(Childless, Node):
Fred Drake1f549022000-09-24 05:21:58 +0000969 nodeType = Node.PROCESSING_INSTRUCTION_NODE
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100970 __slots__ = ('target', 'data')
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000971
Fred Drake1f549022000-09-24 05:21:58 +0000972 def __init__(self, target, data):
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100973 self.target = target
974 self.data = data
Fred Drake55c38192000-06-29 19:39:57 +0000975
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100976 # nodeValue is an alias for data
977 def _get_nodeValue(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000978 return self.data
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100979 def _set_nodeValue(self, value):
Raymond Hettinger92a40552014-06-15 14:48:19 -0700980 self.data = value
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100981 nodeValue = property(_get_nodeValue, _set_nodeValue)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000982
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100983 # nodeName is an alias for target
984 def _get_nodeName(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000985 return self.target
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100986 def _set_nodeName(self, value):
987 self.target = value
988 nodeName = property(_get_nodeName, _set_nodeName)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000989
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000990 def writexml(self, writer, indent="", addindent="", newl=""):
991 writer.write("%s<?%s %s?>%s" % (indent,self.target, self.data, newl))
Fred Drake55c38192000-06-29 19:39:57 +0000992
Martin v. Löwis787354c2003-01-25 15:28:29 +0000993
994class CharacterData(Childless, Node):
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100995 __slots__=('_data', 'ownerDocument','parentNode', 'previousSibling', 'nextSibling')
996
997 def __init__(self):
998 self.ownerDocument = self.parentNode = None
999 self.previousSibling = self.nextSibling = None
1000 self._data = ''
1001 Node.__init__(self)
1002
Martin v. Löwis787354c2003-01-25 15:28:29 +00001003 def _get_length(self):
1004 return len(self.data)
1005 __len__ = _get_length
1006
1007 def _get_data(self):
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001008 return self._data
Martin v. Löwis787354c2003-01-25 15:28:29 +00001009 def _set_data(self, data):
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001010 self._data = data
Martin v. Löwis787354c2003-01-25 15:28:29 +00001011
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001012 data = nodeValue = property(_get_data, _set_data)
Fred Drake87432f42001-04-04 14:09:46 +00001013
Fred Drake55c38192000-06-29 19:39:57 +00001014 def __repr__(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001015 data = self.data
1016 if len(data) > 10:
Fred Drake1f549022000-09-24 05:21:58 +00001017 dotdotdot = "..."
Fred Drake55c38192000-06-29 19:39:57 +00001018 else:
Fred Drake1f549022000-09-24 05:21:58 +00001019 dotdotdot = ""
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001020 return '<DOM %s node "%r%s">' % (
Martin v. Löwis787354c2003-01-25 15:28:29 +00001021 self.__class__.__name__, data[0:10], dotdotdot)
Fred Drake87432f42001-04-04 14:09:46 +00001022
1023 def substringData(self, offset, count):
1024 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001025 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001026 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001027 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +00001028 if count < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001029 raise xml.dom.IndexSizeErr("count cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001030 return self.data[offset:offset+count]
1031
1032 def appendData(self, arg):
1033 self.data = self.data + arg
Fred Drake87432f42001-04-04 14:09:46 +00001034
1035 def insertData(self, offset, arg):
1036 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001037 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001038 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001039 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +00001040 if arg:
1041 self.data = "%s%s%s" % (
1042 self.data[:offset], arg, self.data[offset:])
Fred Drake87432f42001-04-04 14:09:46 +00001043
1044 def deleteData(self, offset, count):
1045 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001046 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001047 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001048 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +00001049 if count < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001050 raise xml.dom.IndexSizeErr("count cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001051 if count:
1052 self.data = self.data[:offset] + self.data[offset+count:]
Fred Drake87432f42001-04-04 14:09:46 +00001053
1054 def replaceData(self, offset, count, arg):
1055 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001056 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001057 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001058 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +00001059 if count < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001060 raise xml.dom.IndexSizeErr("count cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001061 if count:
1062 self.data = "%s%s%s" % (
1063 self.data[:offset], arg, self.data[offset+count:])
Martin v. Löwis787354c2003-01-25 15:28:29 +00001064
1065defproperty(CharacterData, "length", doc="Length of the string data.")
1066
Fred Drake87432f42001-04-04 14:09:46 +00001067
1068class Text(CharacterData):
Florent Xicluna8cf4b512012-03-05 12:37:02 +01001069 __slots__ = ()
1070
Fred Drake87432f42001-04-04 14:09:46 +00001071 nodeType = Node.TEXT_NODE
1072 nodeName = "#text"
1073 attributes = None
Fred Drake55c38192000-06-29 19:39:57 +00001074
Fred Drakef7cf40d2000-12-14 18:16:11 +00001075 def splitText(self, offset):
1076 if offset < 0 or offset > len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001077 raise xml.dom.IndexSizeErr("illegal offset value")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001078 newText = self.__class__()
1079 newText.data = self.data[offset:]
1080 newText.ownerDocument = self.ownerDocument
Fred Drakef7cf40d2000-12-14 18:16:11 +00001081 next = self.nextSibling
1082 if self.parentNode and self in self.parentNode.childNodes:
1083 if next is None:
1084 self.parentNode.appendChild(newText)
1085 else:
1086 self.parentNode.insertBefore(newText, next)
1087 self.data = self.data[:offset]
1088 return newText
1089
Martin v. Löwis46fa39a2001-02-06 00:14:08 +00001090 def writexml(self, writer, indent="", addindent="", newl=""):
Ezio Melotti8008f2a2011-11-18 17:34:26 +02001091 _write_data(writer, "%s%s%s" % (indent, self.data, newl))
Fred Drake55c38192000-06-29 19:39:57 +00001092
Martin v. Löwis787354c2003-01-25 15:28:29 +00001093 # DOM Level 3 (WD 9 April 2002)
1094
1095 def _get_wholeText(self):
1096 L = [self.data]
1097 n = self.previousSibling
1098 while n is not None:
1099 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1100 L.insert(0, n.data)
1101 n = n.previousSibling
1102 else:
1103 break
1104 n = self.nextSibling
1105 while n is not None:
1106 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1107 L.append(n.data)
1108 n = n.nextSibling
1109 else:
1110 break
1111 return ''.join(L)
1112
1113 def replaceWholeText(self, content):
1114 # XXX This needs to be seriously changed if minidom ever
1115 # supports EntityReference nodes.
1116 parent = self.parentNode
1117 n = self.previousSibling
1118 while n is not None:
1119 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1120 next = n.previousSibling
1121 parent.removeChild(n)
1122 n = next
1123 else:
1124 break
1125 n = self.nextSibling
1126 if not content:
1127 parent.removeChild(self)
1128 while n is not None:
1129 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1130 next = n.nextSibling
1131 parent.removeChild(n)
1132 n = next
1133 else:
1134 break
1135 if content:
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001136 self.data = content
Martin v. Löwis787354c2003-01-25 15:28:29 +00001137 return self
1138 else:
1139 return None
1140
1141 def _get_isWhitespaceInElementContent(self):
1142 if self.data.strip():
1143 return False
1144 elem = _get_containing_element(self)
1145 if elem is None:
1146 return False
1147 info = self.ownerDocument._get_elem_info(elem)
1148 if info is None:
1149 return False
1150 else:
1151 return info.isElementContent()
1152
1153defproperty(Text, "isWhitespaceInElementContent",
1154 doc="True iff this text node contains only whitespace"
1155 " and is in element content.")
1156defproperty(Text, "wholeText",
1157 doc="The text of all logically-adjacent text nodes.")
1158
1159
1160def _get_containing_element(node):
1161 c = node.parentNode
1162 while c is not None:
1163 if c.nodeType == Node.ELEMENT_NODE:
1164 return c
1165 c = c.parentNode
1166 return None
1167
1168def _get_containing_entref(node):
1169 c = node.parentNode
1170 while c is not None:
1171 if c.nodeType == Node.ENTITY_REFERENCE_NODE:
1172 return c
1173 c = c.parentNode
1174 return None
1175
1176
Alex Martelli0ee43512006-08-21 19:53:20 +00001177class Comment(CharacterData):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001178 nodeType = Node.COMMENT_NODE
1179 nodeName = "#comment"
1180
1181 def __init__(self, data):
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001182 CharacterData.__init__(self)
1183 self._data = data
Martin v. Löwis787354c2003-01-25 15:28:29 +00001184
1185 def writexml(self, writer, indent="", addindent="", newl=""):
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001186 if "--" in self.data:
1187 raise ValueError("'--' is not allowed in a comment node")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001188 writer.write("%s<!--%s-->%s" % (indent, self.data, newl))
1189
Fred Drake87432f42001-04-04 14:09:46 +00001190
1191class CDATASection(Text):
Florent Xicluna8cf4b512012-03-05 12:37:02 +01001192 __slots__ = ()
1193
Fred Drake87432f42001-04-04 14:09:46 +00001194 nodeType = Node.CDATA_SECTION_NODE
1195 nodeName = "#cdata-section"
1196
1197 def writexml(self, writer, indent="", addindent="", newl=""):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001198 if self.data.find("]]>") >= 0:
1199 raise ValueError("']]>' not allowed in a CDATA section")
Guido van Rossum5b5e0b92001-09-19 13:28:25 +00001200 writer.write("<![CDATA[%s]]>" % self.data)
Fred Drake87432f42001-04-04 14:09:46 +00001201
1202
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001203class ReadOnlySequentialNamedNodeMap(object):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001204 __slots__ = '_seq',
1205
1206 def __init__(self, seq=()):
1207 # seq should be a list or tuple
1208 self._seq = seq
1209
1210 def __len__(self):
1211 return len(self._seq)
1212
1213 def _get_length(self):
1214 return len(self._seq)
1215
1216 def getNamedItem(self, name):
1217 for n in self._seq:
1218 if n.nodeName == name:
1219 return n
1220
1221 def getNamedItemNS(self, namespaceURI, localName):
1222 for n in self._seq:
1223 if n.namespaceURI == namespaceURI and n.localName == localName:
1224 return n
1225
1226 def __getitem__(self, name_or_tuple):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001227 if isinstance(name_or_tuple, tuple):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001228 node = self.getNamedItemNS(*name_or_tuple)
1229 else:
1230 node = self.getNamedItem(name_or_tuple)
1231 if node is None:
Collin Winter70e79802007-08-24 18:57:22 +00001232 raise KeyError(name_or_tuple)
Martin v. Löwis787354c2003-01-25 15:28:29 +00001233 return node
1234
1235 def item(self, index):
1236 if index < 0:
1237 return None
1238 try:
1239 return self._seq[index]
1240 except IndexError:
1241 return None
1242
1243 def removeNamedItem(self, name):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001244 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001245 "NamedNodeMap instance is read-only")
1246
1247 def removeNamedItemNS(self, namespaceURI, localName):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001248 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001249 "NamedNodeMap instance is read-only")
1250
1251 def setNamedItem(self, node):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001252 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001253 "NamedNodeMap instance is read-only")
1254
1255 def setNamedItemNS(self, node):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001256 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001257 "NamedNodeMap instance is read-only")
1258
1259 def __getstate__(self):
1260 return [self._seq]
1261
1262 def __setstate__(self, state):
1263 self._seq = state[0]
1264
1265defproperty(ReadOnlySequentialNamedNodeMap, "length",
1266 doc="Number of entries in the NamedNodeMap.")
Paul Prescod73678da2000-07-01 04:58:47 +00001267
Fred Drakef7cf40d2000-12-14 18:16:11 +00001268
Martin v. Löwis787354c2003-01-25 15:28:29 +00001269class Identified:
1270 """Mix-in class that supports the publicId and systemId attributes."""
1271
Florent Xicluna8cf4b512012-03-05 12:37:02 +01001272 __slots__ = 'publicId', 'systemId'
Martin v. Löwis787354c2003-01-25 15:28:29 +00001273
1274 def _identified_mixin_init(self, publicId, systemId):
1275 self.publicId = publicId
1276 self.systemId = systemId
1277
1278 def _get_publicId(self):
1279 return self.publicId
1280
1281 def _get_systemId(self):
1282 return self.systemId
1283
1284class DocumentType(Identified, Childless, Node):
Fred Drakef7cf40d2000-12-14 18:16:11 +00001285 nodeType = Node.DOCUMENT_TYPE_NODE
1286 nodeValue = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001287 name = None
1288 publicId = None
1289 systemId = None
Fred Drakedc806702001-04-05 14:41:30 +00001290 internalSubset = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001291
1292 def __init__(self, qualifiedName):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001293 self.entities = ReadOnlySequentialNamedNodeMap()
1294 self.notations = ReadOnlySequentialNamedNodeMap()
Fred Drakef7cf40d2000-12-14 18:16:11 +00001295 if qualifiedName:
1296 prefix, localname = _nssplit(qualifiedName)
1297 self.name = localname
Martin v. Löwis787354c2003-01-25 15:28:29 +00001298 self.nodeName = self.name
1299
1300 def _get_internalSubset(self):
1301 return self.internalSubset
1302
1303 def cloneNode(self, deep):
1304 if self.ownerDocument is None:
1305 # it's ok
1306 clone = DocumentType(None)
1307 clone.name = self.name
1308 clone.nodeName = self.name
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001309 operation = xml.dom.UserDataHandler.NODE_CLONED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001310 if deep:
1311 clone.entities._seq = []
1312 clone.notations._seq = []
1313 for n in self.notations._seq:
1314 notation = Notation(n.nodeName, n.publicId, n.systemId)
1315 clone.notations._seq.append(notation)
1316 n._call_user_data_handler(operation, n, notation)
1317 for e in self.entities._seq:
1318 entity = Entity(e.nodeName, e.publicId, e.systemId,
1319 e.notationName)
1320 entity.actualEncoding = e.actualEncoding
1321 entity.encoding = e.encoding
1322 entity.version = e.version
1323 clone.entities._seq.append(entity)
1324 e._call_user_data_handler(operation, n, entity)
1325 self._call_user_data_handler(operation, self, clone)
1326 return clone
1327 else:
1328 return None
1329
1330 def writexml(self, writer, indent="", addindent="", newl=""):
1331 writer.write("<!DOCTYPE ")
1332 writer.write(self.name)
1333 if self.publicId:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001334 writer.write("%s PUBLIC '%s'%s '%s'"
1335 % (newl, self.publicId, newl, self.systemId))
Martin v. Löwis787354c2003-01-25 15:28:29 +00001336 elif self.systemId:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001337 writer.write("%s SYSTEM '%s'" % (newl, self.systemId))
Martin v. Löwis787354c2003-01-25 15:28:29 +00001338 if self.internalSubset is not None:
1339 writer.write(" [")
1340 writer.write(self.internalSubset)
1341 writer.write("]")
Georg Brandl175a7dc2005-08-25 22:02:43 +00001342 writer.write(">"+newl)
Martin v. Löwis787354c2003-01-25 15:28:29 +00001343
1344class Entity(Identified, Node):
1345 attributes = None
1346 nodeType = Node.ENTITY_NODE
1347 nodeValue = None
1348
1349 actualEncoding = None
1350 encoding = None
1351 version = None
1352
1353 def __init__(self, name, publicId, systemId, notation):
1354 self.nodeName = name
1355 self.notationName = notation
1356 self.childNodes = NodeList()
1357 self._identified_mixin_init(publicId, systemId)
1358
1359 def _get_actualEncoding(self):
1360 return self.actualEncoding
1361
1362 def _get_encoding(self):
1363 return self.encoding
1364
1365 def _get_version(self):
1366 return self.version
1367
1368 def appendChild(self, newChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001369 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001370 "cannot append children to an entity node")
1371
1372 def insertBefore(self, newChild, refChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001373 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001374 "cannot insert children below an entity node")
1375
1376 def removeChild(self, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001377 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001378 "cannot remove children from an entity node")
1379
1380 def replaceChild(self, newChild, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001381 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001382 "cannot replace children of an entity node")
1383
1384class Notation(Identified, Childless, Node):
1385 nodeType = Node.NOTATION_NODE
1386 nodeValue = None
1387
1388 def __init__(self, name, publicId, systemId):
1389 self.nodeName = name
1390 self._identified_mixin_init(publicId, systemId)
Fred Drakef7cf40d2000-12-14 18:16:11 +00001391
1392
Martin v. Löwis787354c2003-01-25 15:28:29 +00001393class DOMImplementation(DOMImplementationLS):
1394 _features = [("core", "1.0"),
1395 ("core", "2.0"),
Martin v. Löwis787354c2003-01-25 15:28:29 +00001396 ("core", None),
1397 ("xml", "1.0"),
1398 ("xml", "2.0"),
Martin v. Löwis787354c2003-01-25 15:28:29 +00001399 ("xml", None),
1400 ("ls-load", "3.0"),
1401 ("ls-load", None),
1402 ]
1403
Fred Drakef7cf40d2000-12-14 18:16:11 +00001404 def hasFeature(self, feature, version):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001405 if version == "":
1406 version = None
1407 return (feature.lower(), version) in self._features
Fred Drakef7cf40d2000-12-14 18:16:11 +00001408
1409 def createDocument(self, namespaceURI, qualifiedName, doctype):
1410 if doctype and doctype.parentNode is not None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001411 raise xml.dom.WrongDocumentErr(
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +00001412 "doctype object owned by another DOM tree")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001413 doc = self._create_document()
1414
1415 add_root_element = not (namespaceURI is None
1416 and qualifiedName is None
1417 and doctype is None)
1418
1419 if not qualifiedName and add_root_element:
Martin v. Löwisb417be22001-02-06 01:16:06 +00001420 # The spec is unclear what to raise here; SyntaxErr
1421 # would be the other obvious candidate. Since Xerces raises
1422 # InvalidCharacterErr, and since SyntaxErr is not listed
1423 # for createDocument, that seems to be the better choice.
1424 # XXX: need to check for illegal characters here and in
1425 # createElement.
Martin v. Löwis787354c2003-01-25 15:28:29 +00001426
1427 # DOM Level III clears this up when talking about the return value
1428 # of this function. If namespaceURI, qName and DocType are
1429 # Null the document is returned without a document element
1430 # Otherwise if doctype or namespaceURI are not None
1431 # Then we go back to the above problem
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001432 raise xml.dom.InvalidCharacterErr("Element with no name")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001433
1434 if add_root_element:
1435 prefix, localname = _nssplit(qualifiedName)
1436 if prefix == "xml" \
1437 and namespaceURI != "http://www.w3.org/XML/1998/namespace":
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001438 raise xml.dom.NamespaceErr("illegal use of 'xml' prefix")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001439 if prefix and not namespaceURI:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001440 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001441 "illegal use of prefix without namespaces")
1442 element = doc.createElementNS(namespaceURI, qualifiedName)
1443 if doctype:
1444 doc.appendChild(doctype)
1445 doc.appendChild(element)
1446
1447 if doctype:
1448 doctype.parentNode = doctype.ownerDocument = doc
1449
Fred Drakef7cf40d2000-12-14 18:16:11 +00001450 doc.doctype = doctype
1451 doc.implementation = self
1452 return doc
1453
1454 def createDocumentType(self, qualifiedName, publicId, systemId):
1455 doctype = DocumentType(qualifiedName)
1456 doctype.publicId = publicId
1457 doctype.systemId = systemId
1458 return doctype
1459
Martin v. Löwis787354c2003-01-25 15:28:29 +00001460 # DOM Level 3 (WD 9 April 2002)
1461
1462 def getInterface(self, feature):
1463 if self.hasFeature(feature, None):
1464 return self
1465 else:
1466 return None
1467
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001468 # internal
Martin v. Löwis787354c2003-01-25 15:28:29 +00001469 def _create_document(self):
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001470 return Document()
Fred Drakef7cf40d2000-12-14 18:16:11 +00001471
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001472class ElementInfo(object):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001473 """Object that represents content-model information for an element.
1474
1475 This implementation is not expected to be used in practice; DOM
1476 builders should provide implementations which do the right thing
1477 using information available to it.
1478
1479 """
1480
1481 __slots__ = 'tagName',
1482
1483 def __init__(self, name):
1484 self.tagName = name
1485
1486 def getAttributeType(self, aname):
1487 return _no_type
1488
1489 def getAttributeTypeNS(self, namespaceURI, localName):
1490 return _no_type
1491
1492 def isElementContent(self):
1493 return False
1494
1495 def isEmpty(self):
1496 """Returns true iff this element is declared to have an EMPTY
1497 content model."""
1498 return False
1499
1500 def isId(self, aname):
Ezio Melotti42da6632011-03-15 05:18:48 +02001501 """Returns true iff the named attribute is a DTD-style ID."""
Martin v. Löwis787354c2003-01-25 15:28:29 +00001502 return False
1503
1504 def isIdNS(self, namespaceURI, localName):
1505 """Returns true iff the identified attribute is a DTD-style ID."""
1506 return False
1507
1508 def __getstate__(self):
1509 return self.tagName
1510
1511 def __setstate__(self, state):
1512 self.tagName = state
1513
1514def _clear_id_cache(node):
1515 if node.nodeType == Node.DOCUMENT_NODE:
1516 node._id_cache.clear()
1517 node._id_search_stack = None
1518 elif _in_document(node):
1519 node.ownerDocument._id_cache.clear()
1520 node.ownerDocument._id_search_stack= None
1521
1522class Document(Node, DocumentLS):
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001523 __slots__ = ('_elem_info', 'doctype',
1524 '_id_search_stack', 'childNodes', '_id_cache')
Martin v. Löwis787354c2003-01-25 15:28:29 +00001525 _child_node_types = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE,
1526 Node.COMMENT_NODE, Node.DOCUMENT_TYPE_NODE)
1527
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001528 implementation = DOMImplementation()
Fred Drake1f549022000-09-24 05:21:58 +00001529 nodeType = Node.DOCUMENT_NODE
Fred Drake4ccf4a12000-11-21 22:02:22 +00001530 nodeName = "#document"
1531 nodeValue = None
1532 attributes = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001533 parentNode = None
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001534 previousSibling = nextSibling = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001535
Martin v. Löwis787354c2003-01-25 15:28:29 +00001536
1537 # Document attributes from Level 3 (WD 9 April 2002)
1538
1539 actualEncoding = None
1540 encoding = None
1541 standalone = None
1542 version = None
1543 strictErrorChecking = False
1544 errorHandler = None
1545 documentURI = None
1546
1547 _magic_id_count = 0
1548
1549 def __init__(self):
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001550 self.doctype = None
Martin v. Löwis787354c2003-01-25 15:28:29 +00001551 self.childNodes = NodeList()
1552 # mapping of (namespaceURI, localName) -> ElementInfo
1553 # and tagName -> ElementInfo
1554 self._elem_info = {}
1555 self._id_cache = {}
1556 self._id_search_stack = None
1557
1558 def _get_elem_info(self, element):
1559 if element.namespaceURI:
1560 key = element.namespaceURI, element.localName
1561 else:
1562 key = element.tagName
1563 return self._elem_info.get(key)
1564
1565 def _get_actualEncoding(self):
1566 return self.actualEncoding
1567
1568 def _get_doctype(self):
1569 return self.doctype
1570
1571 def _get_documentURI(self):
1572 return self.documentURI
1573
1574 def _get_encoding(self):
1575 return self.encoding
1576
1577 def _get_errorHandler(self):
1578 return self.errorHandler
1579
1580 def _get_standalone(self):
1581 return self.standalone
1582
1583 def _get_strictErrorChecking(self):
1584 return self.strictErrorChecking
1585
1586 def _get_version(self):
1587 return self.version
Fred Drake55c38192000-06-29 19:39:57 +00001588
Fred Drake1f549022000-09-24 05:21:58 +00001589 def appendChild(self, node):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001590 if node.nodeType not in self._child_node_types:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001591 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001592 "%s cannot be child of %s" % (repr(node), repr(self)))
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001593 if node.parentNode is not None:
Martin v. Löwis787354c2003-01-25 15:28:29 +00001594 # This needs to be done before the next test since this
1595 # may *be* the document element, in which case it should
1596 # end up re-ordered to the end.
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001597 node.parentNode.removeChild(node)
1598
Fred Drakef7cf40d2000-12-14 18:16:11 +00001599 if node.nodeType == Node.ELEMENT_NODE \
1600 and self._get_documentElement():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001601 raise xml.dom.HierarchyRequestErr(
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +00001602 "two document elements disallowed")
Fred Drake4ccf4a12000-11-21 22:02:22 +00001603 return Node.appendChild(self, node)
Paul Prescod73678da2000-07-01 04:58:47 +00001604
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001605 def removeChild(self, oldChild):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001606 try:
1607 self.childNodes.remove(oldChild)
1608 except ValueError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001609 raise xml.dom.NotFoundErr()
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001610 oldChild.nextSibling = oldChild.previousSibling = None
1611 oldChild.parentNode = None
1612 if self.documentElement is oldChild:
1613 self.documentElement = None
Martin v. Löwis52ce0d02001-01-27 08:47:37 +00001614
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001615 return oldChild
1616
Fred Drakef7cf40d2000-12-14 18:16:11 +00001617 def _get_documentElement(self):
1618 for node in self.childNodes:
1619 if node.nodeType == Node.ELEMENT_NODE:
1620 return node
1621
1622 def unlink(self):
1623 if self.doctype is not None:
1624 self.doctype.unlink()
1625 self.doctype = None
1626 Node.unlink(self)
1627
Martin v. Löwis787354c2003-01-25 15:28:29 +00001628 def cloneNode(self, deep):
1629 if not deep:
1630 return None
1631 clone = self.implementation.createDocument(None, None, None)
1632 clone.encoding = self.encoding
1633 clone.standalone = self.standalone
1634 clone.version = self.version
1635 for n in self.childNodes:
1636 childclone = _clone_node(n, deep, clone)
1637 assert childclone.ownerDocument.isSameNode(clone)
1638 clone.childNodes.append(childclone)
1639 if childclone.nodeType == Node.DOCUMENT_NODE:
1640 assert clone.documentElement is None
1641 elif childclone.nodeType == Node.DOCUMENT_TYPE_NODE:
1642 assert clone.doctype is None
1643 clone.doctype = childclone
1644 childclone.parentNode = clone
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001645 self._call_user_data_handler(xml.dom.UserDataHandler.NODE_CLONED,
Martin v. Löwis787354c2003-01-25 15:28:29 +00001646 self, clone)
1647 return clone
1648
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001649 def createDocumentFragment(self):
1650 d = DocumentFragment()
Martin v. Löwis787354c2003-01-25 15:28:29 +00001651 d.ownerDocument = self
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001652 return d
Fred Drake55c38192000-06-29 19:39:57 +00001653
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001654 def createElement(self, tagName):
1655 e = Element(tagName)
1656 e.ownerDocument = self
1657 return e
Fred Drake55c38192000-06-29 19:39:57 +00001658
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001659 def createTextNode(self, data):
Christian Heimesc9543e42007-11-28 08:28:28 +00001660 if not isinstance(data, str):
Collin Winter70e79802007-08-24 18:57:22 +00001661 raise TypeError("node contents must be a string")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001662 t = Text()
1663 t.data = data
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001664 t.ownerDocument = self
1665 return t
Fred Drake55c38192000-06-29 19:39:57 +00001666
Fred Drake87432f42001-04-04 14:09:46 +00001667 def createCDATASection(self, data):
Christian Heimesc9543e42007-11-28 08:28:28 +00001668 if not isinstance(data, str):
Collin Winter70e79802007-08-24 18:57:22 +00001669 raise TypeError("node contents must be a string")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001670 c = CDATASection()
1671 c.data = data
Fred Drake87432f42001-04-04 14:09:46 +00001672 c.ownerDocument = self
1673 return c
1674
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001675 def createComment(self, data):
1676 c = Comment(data)
1677 c.ownerDocument = self
1678 return c
Fred Drake55c38192000-06-29 19:39:57 +00001679
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001680 def createProcessingInstruction(self, target, data):
1681 p = ProcessingInstruction(target, data)
1682 p.ownerDocument = self
1683 return p
1684
1685 def createAttribute(self, qName):
1686 a = Attr(qName)
1687 a.ownerDocument = self
Martin v. Löwiscb67ea12001-03-31 16:30:40 +00001688 a.value = ""
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001689 return a
Fred Drake55c38192000-06-29 19:39:57 +00001690
1691 def createElementNS(self, namespaceURI, qualifiedName):
Fred Drake4ccf4a12000-11-21 22:02:22 +00001692 prefix, localName = _nssplit(qualifiedName)
Martin v. Löwis787354c2003-01-25 15:28:29 +00001693 e = Element(qualifiedName, namespaceURI, prefix)
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001694 e.ownerDocument = self
1695 return e
Fred Drake55c38192000-06-29 19:39:57 +00001696
1697 def createAttributeNS(self, namespaceURI, qualifiedName):
Fred Drake4ccf4a12000-11-21 22:02:22 +00001698 prefix, localName = _nssplit(qualifiedName)
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001699 a = Attr(qualifiedName, namespaceURI, localName, prefix)
1700 a.ownerDocument = self
Martin v. Löwiscb67ea12001-03-31 16:30:40 +00001701 a.value = ""
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001702 return a
Fred Drake55c38192000-06-29 19:39:57 +00001703
Martin v. Löwis787354c2003-01-25 15:28:29 +00001704 # A couple of implementation-specific helpers to create node types
1705 # not supported by the W3C DOM specs:
1706
1707 def _create_entity(self, name, publicId, systemId, notationName):
1708 e = Entity(name, publicId, systemId, notationName)
1709 e.ownerDocument = self
1710 return e
1711
1712 def _create_notation(self, name, publicId, systemId):
1713 n = Notation(name, publicId, systemId)
1714 n.ownerDocument = self
1715 return n
1716
1717 def getElementById(self, id):
Guido van Rossum1b01e5c2006-08-19 02:45:06 +00001718 if id in self._id_cache:
Martin v. Löwis787354c2003-01-25 15:28:29 +00001719 return self._id_cache[id]
1720 if not (self._elem_info or self._magic_id_count):
1721 return None
1722
1723 stack = self._id_search_stack
1724 if stack is None:
1725 # we never searched before, or the cache has been cleared
1726 stack = [self.documentElement]
1727 self._id_search_stack = stack
1728 elif not stack:
1729 # Previous search was completed and cache is still valid;
1730 # no matching node.
1731 return None
1732
1733 result = None
1734 while stack:
1735 node = stack.pop()
1736 # add child elements to stack for continued searching
1737 stack.extend([child for child in node.childNodes
1738 if child.nodeType in _nodeTypes_with_children])
1739 # check this node
1740 info = self._get_elem_info(node)
1741 if info:
1742 # We have to process all ID attributes before
1743 # returning in order to get all the attributes set to
1744 # be IDs using Element.setIdAttribute*().
1745 for attr in node.attributes.values():
1746 if attr.namespaceURI:
1747 if info.isIdNS(attr.namespaceURI, attr.localName):
1748 self._id_cache[attr.value] = node
1749 if attr.value == id:
1750 result = node
1751 elif not node._magic_id_nodes:
1752 break
1753 elif info.isId(attr.name):
1754 self._id_cache[attr.value] = node
1755 if attr.value == id:
1756 result = node
1757 elif not node._magic_id_nodes:
1758 break
1759 elif attr._is_id:
1760 self._id_cache[attr.value] = node
1761 if attr.value == id:
1762 result = node
1763 elif node._magic_id_nodes == 1:
1764 break
1765 elif node._magic_id_nodes:
1766 for attr in node.attributes.values():
1767 if attr._is_id:
1768 self._id_cache[attr.value] = node
1769 if attr.value == id:
1770 result = node
1771 if result is not None:
1772 break
1773 return result
1774
Fred Drake1f549022000-09-24 05:21:58 +00001775 def getElementsByTagName(self, name):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001776 return _get_elements_by_tagName_helper(self, name, NodeList())
Fred Drakefbe7b4f2001-07-04 06:25:53 +00001777
1778 def getElementsByTagNameNS(self, namespaceURI, localName):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001779 return _get_elements_by_tagName_ns_helper(
1780 self, namespaceURI, localName, NodeList())
1781
1782 def isSupported(self, feature, version):
1783 return self.implementation.hasFeature(feature, version)
1784
1785 def importNode(self, node, deep):
1786 if node.nodeType == Node.DOCUMENT_NODE:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001787 raise xml.dom.NotSupportedErr("cannot import document nodes")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001788 elif node.nodeType == Node.DOCUMENT_TYPE_NODE:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001789 raise xml.dom.NotSupportedErr("cannot import document type nodes")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001790 return _clone_node(node, deep, self)
Fred Drake55c38192000-06-29 19:39:57 +00001791
Eli Bendersky8a805022012-07-13 09:52:39 +03001792 def writexml(self, writer, indent="", addindent="", newl="", encoding=None):
Martin v. Löwis7d650ca2002-06-30 15:05:00 +00001793 if encoding is None:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001794 writer.write('<?xml version="1.0" ?>'+newl)
Martin v. Löwis7d650ca2002-06-30 15:05:00 +00001795 else:
Eli Bendersky8a805022012-07-13 09:52:39 +03001796 writer.write('<?xml version="1.0" encoding="%s"?>%s' % (
1797 encoding, newl))
Fred Drake55c38192000-06-29 19:39:57 +00001798 for node in self.childNodes:
Martin v. Löwis46fa39a2001-02-06 00:14:08 +00001799 node.writexml(writer, indent, addindent, newl)
Fred Drake55c38192000-06-29 19:39:57 +00001800
Martin v. Löwis787354c2003-01-25 15:28:29 +00001801 # DOM Level 3 (WD 9 April 2002)
1802
1803 def renameNode(self, n, namespaceURI, name):
1804 if n.ownerDocument is not self:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001805 raise xml.dom.WrongDocumentErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001806 "cannot rename nodes from other documents;\n"
1807 "expected %s,\nfound %s" % (self, n.ownerDocument))
1808 if n.nodeType not in (Node.ELEMENT_NODE, Node.ATTRIBUTE_NODE):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001809 raise xml.dom.NotSupportedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001810 "renameNode() only applies to element and attribute nodes")
1811 if namespaceURI != EMPTY_NAMESPACE:
1812 if ':' in name:
1813 prefix, localName = name.split(':', 1)
1814 if ( prefix == "xmlns"
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001815 and namespaceURI != xml.dom.XMLNS_NAMESPACE):
1816 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001817 "illegal use of 'xmlns' prefix")
1818 else:
1819 if ( name == "xmlns"
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001820 and namespaceURI != xml.dom.XMLNS_NAMESPACE
Martin v. Löwis787354c2003-01-25 15:28:29 +00001821 and n.nodeType == Node.ATTRIBUTE_NODE):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001822 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001823 "illegal use of the 'xmlns' attribute")
1824 prefix = None
1825 localName = name
1826 else:
1827 prefix = None
1828 localName = None
1829 if n.nodeType == Node.ATTRIBUTE_NODE:
1830 element = n.ownerElement
1831 if element is not None:
1832 is_id = n._is_id
1833 element.removeAttributeNode(n)
1834 else:
1835 element = None
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001836 n.prefix = prefix
1837 n._localName = localName
1838 n.namespaceURI = namespaceURI
1839 n.nodeName = name
Martin v. Löwis787354c2003-01-25 15:28:29 +00001840 if n.nodeType == Node.ELEMENT_NODE:
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001841 n.tagName = name
Martin v. Löwis787354c2003-01-25 15:28:29 +00001842 else:
1843 # attribute node
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001844 n.name = name
Martin v. Löwis787354c2003-01-25 15:28:29 +00001845 if element is not None:
1846 element.setAttributeNode(n)
1847 if is_id:
1848 element.setIdAttributeNode(n)
1849 # It's not clear from a semantic perspective whether we should
1850 # call the user data handlers for the NODE_RENAMED event since
1851 # we're re-using the existing node. The draft spec has been
1852 # interpreted as meaning "no, don't call the handler unless a
1853 # new node is created."
1854 return n
1855
1856defproperty(Document, "documentElement",
1857 doc="Top-level element of this document.")
1858
1859
1860def _clone_node(node, deep, newOwnerDocument):
1861 """
1862 Clone a node and give it the new owner document.
1863 Called by Node.cloneNode and Document.importNode
1864 """
1865 if node.ownerDocument.isSameNode(newOwnerDocument):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001866 operation = xml.dom.UserDataHandler.NODE_CLONED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001867 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001868 operation = xml.dom.UserDataHandler.NODE_IMPORTED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001869 if node.nodeType == Node.ELEMENT_NODE:
1870 clone = newOwnerDocument.createElementNS(node.namespaceURI,
1871 node.nodeName)
1872 for attr in node.attributes.values():
1873 clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value)
1874 a = clone.getAttributeNodeNS(attr.namespaceURI, attr.localName)
1875 a.specified = attr.specified
1876
1877 if deep:
1878 for child in node.childNodes:
1879 c = _clone_node(child, deep, newOwnerDocument)
1880 clone.appendChild(c)
1881
1882 elif node.nodeType == Node.DOCUMENT_FRAGMENT_NODE:
1883 clone = newOwnerDocument.createDocumentFragment()
1884 if deep:
1885 for child in node.childNodes:
1886 c = _clone_node(child, deep, newOwnerDocument)
1887 clone.appendChild(c)
1888
1889 elif node.nodeType == Node.TEXT_NODE:
1890 clone = newOwnerDocument.createTextNode(node.data)
1891 elif node.nodeType == Node.CDATA_SECTION_NODE:
1892 clone = newOwnerDocument.createCDATASection(node.data)
1893 elif node.nodeType == Node.PROCESSING_INSTRUCTION_NODE:
1894 clone = newOwnerDocument.createProcessingInstruction(node.target,
1895 node.data)
1896 elif node.nodeType == Node.COMMENT_NODE:
1897 clone = newOwnerDocument.createComment(node.data)
1898 elif node.nodeType == Node.ATTRIBUTE_NODE:
1899 clone = newOwnerDocument.createAttributeNS(node.namespaceURI,
1900 node.nodeName)
1901 clone.specified = True
1902 clone.value = node.value
1903 elif node.nodeType == Node.DOCUMENT_TYPE_NODE:
1904 assert node.ownerDocument is not newOwnerDocument
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001905 operation = xml.dom.UserDataHandler.NODE_IMPORTED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001906 clone = newOwnerDocument.implementation.createDocumentType(
1907 node.name, node.publicId, node.systemId)
1908 clone.ownerDocument = newOwnerDocument
1909 if deep:
1910 clone.entities._seq = []
1911 clone.notations._seq = []
1912 for n in node.notations._seq:
1913 notation = Notation(n.nodeName, n.publicId, n.systemId)
1914 notation.ownerDocument = newOwnerDocument
1915 clone.notations._seq.append(notation)
1916 if hasattr(n, '_call_user_data_handler'):
1917 n._call_user_data_handler(operation, n, notation)
1918 for e in node.entities._seq:
1919 entity = Entity(e.nodeName, e.publicId, e.systemId,
1920 e.notationName)
1921 entity.actualEncoding = e.actualEncoding
1922 entity.encoding = e.encoding
1923 entity.version = e.version
1924 entity.ownerDocument = newOwnerDocument
1925 clone.entities._seq.append(entity)
1926 if hasattr(e, '_call_user_data_handler'):
1927 e._call_user_data_handler(operation, n, entity)
1928 else:
1929 # Note the cloning of Document and DocumentType nodes is
Ezio Melotti13925002011-03-16 11:05:33 +02001930 # implementation specific. minidom handles those cases
Martin v. Löwis787354c2003-01-25 15:28:29 +00001931 # directly in the cloneNode() methods.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001932 raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node))
Martin v. Löwis787354c2003-01-25 15:28:29 +00001933
1934 # Check for _call_user_data_handler() since this could conceivably
1935 # used with other DOM implementations (one of the FourThought
1936 # DOMs, perhaps?).
1937 if hasattr(node, '_call_user_data_handler'):
1938 node._call_user_data_handler(operation, node, clone)
1939 return clone
1940
1941
1942def _nssplit(qualifiedName):
1943 fields = qualifiedName.split(':', 1)
1944 if len(fields) == 2:
1945 return fields
1946 else:
1947 return (None, fields[0])
1948
1949
Martin v. Löwis787354c2003-01-25 15:28:29 +00001950def _do_pulldom_parse(func, args, kwargs):
Raymond Hettingerff41c482003-04-06 09:01:11 +00001951 events = func(*args, **kwargs)
Fred Drake1f549022000-09-24 05:21:58 +00001952 toktype, rootNode = events.getEvent()
1953 events.expandNode(rootNode)
Martin v. Löwisb417be22001-02-06 01:16:06 +00001954 events.clear()
Fred Drake55c38192000-06-29 19:39:57 +00001955 return rootNode
1956
Martin v. Löwis787354c2003-01-25 15:28:29 +00001957def parse(file, parser=None, bufsize=None):
Fred Drakef7cf40d2000-12-14 18:16:11 +00001958 """Parse a file into a DOM by filename or file object."""
Martin v. Löwis787354c2003-01-25 15:28:29 +00001959 if parser is None and not bufsize:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001960 from xml.dom import expatbuilder
Martin v. Löwis787354c2003-01-25 15:28:29 +00001961 return expatbuilder.parse(file)
1962 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001963 from xml.dom import pulldom
Raymond Hettingerff41c482003-04-06 09:01:11 +00001964 return _do_pulldom_parse(pulldom.parse, (file,),
Martin v. Löwis787354c2003-01-25 15:28:29 +00001965 {'parser': parser, 'bufsize': bufsize})
Fred Drake55c38192000-06-29 19:39:57 +00001966
Martin v. Löwis787354c2003-01-25 15:28:29 +00001967def parseString(string, parser=None):
Fred Drakef7cf40d2000-12-14 18:16:11 +00001968 """Parse a file into a DOM from a string."""
Martin v. Löwis787354c2003-01-25 15:28:29 +00001969 if parser is None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001970 from xml.dom import expatbuilder
Martin v. Löwis787354c2003-01-25 15:28:29 +00001971 return expatbuilder.parseString(string)
1972 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001973 from xml.dom import pulldom
Martin v. Löwis787354c2003-01-25 15:28:29 +00001974 return _do_pulldom_parse(pulldom.parseString, (string,),
1975 {'parser': parser})
Martin v. Löwis7edbd4f2001-02-22 14:05:50 +00001976
Martin v. Löwis787354c2003-01-25 15:28:29 +00001977def getDOMImplementation(features=None):
1978 if features:
Christian Heimesc9543e42007-11-28 08:28:28 +00001979 if isinstance(features, str):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001980 features = domreg._parse_feature_string(features)
1981 for f, v in features:
1982 if not Document.implementation.hasFeature(f, v):
1983 return None
Martin v. Löwis7edbd4f2001-02-22 14:05:50 +00001984 return Document.implementation