blob: 7e2f88e3609246fc70a2d02766b3367635e8554d [file] [log] [blame]
Fred Drake1f549022000-09-24 05:21:58 +00001"""\
Fred Drakef7cf40d2000-12-14 18:16:11 +00002minidom.py -- a lightweight DOM implementation.
Fred Drake55c38192000-06-29 19:39:57 +00003
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +00004parse("foo.xml")
Paul Prescod623511b2000-07-21 22:05:49 +00005
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +00006parseString("<foo><bar/></foo>")
Paul Prescod623511b2000-07-21 22:05:49 +00007
Fred Drake55c38192000-06-29 19:39:57 +00008Todo:
9=====
10 * convenience methods for getting elements and text.
11 * more testing
12 * bring some of the writer and linearizer code into conformance with this
13 interface
14 * SAX 2 namespaces
15"""
16
Alexandre Vassalotti794652d2008-06-11 22:58:36 +000017import codecs
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):
Martin v. Löwiscb67ea12001-03-31 16:30:40 +000050 # indent = the indentation string to prepend, per level
51 # newl = the newline string to append
Guido van Rossum55b15c92007-08-07 23:03:33 +000052 use_encoding = "utf-8" if encoding is None else encoding
Alexandre Vassalotti794652d2008-06-11 22:58:36 +000053 writer = codecs.getwriter(use_encoding)(io.BytesIO())
Martin v. Löwis7d650ca2002-06-30 15:05:00 +000054 if self.nodeType == Node.DOCUMENT_NODE:
55 # Can pass encoding only to document, to put it into XML header
56 self.writexml(writer, "", indent, newl, encoding)
57 else:
58 self.writexml(writer, "", indent, newl)
Guido van Rossum3e1f85e2007-07-27 18:03:11 +000059 if encoding is None:
Alexandre Vassalotti794652d2008-06-11 22:58:36 +000060 return writer.stream.getvalue().decode(use_encoding)
Guido van Rossum3e1f85e2007-07-27 18:03:11 +000061 else:
Alexandre Vassalotti794652d2008-06-11 22:58:36 +000062 return writer.stream.getvalue()
Martin v. Löwis46fa39a2001-02-06 00:14:08 +000063
Fred Drake1f549022000-09-24 05:21:58 +000064 def hasChildNodes(self):
65 if self.childNodes:
Martin v. Löwis787354c2003-01-25 15:28:29 +000066 return True
Fred Drake1f549022000-09-24 05:21:58 +000067 else:
Martin v. Löwis787354c2003-01-25 15:28:29 +000068 return False
69
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
373 def _get_name(self):
374 return self.name
375
376 def _get_specified(self):
377 return self.specified
378
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100379 def _get_name(self):
380 return self._name
381
382 def _set_name(self, value):
383 self._name = value
384 if self.ownerElement is not None:
385 _clear_id_cache(self.ownerElement)
386
387 nodeName = name = property(_get_name, _set_name)
388
389 def _get_value(self):
390 return self._value
391
392 def _set_value(self, value):
393 self._value = value
394 self.childNodes[0].data = value
395 if self.ownerElement is not None:
396 _clear_id_cache(self.ownerElement)
397 self.childNodes[0].data = value
398
399 nodeValue = value = property(_get_value, _set_value)
400
401 def _get_prefix(self):
402 return self._prefix
Fred Drake55c38192000-06-29 19:39:57 +0000403
Martin v. Löwis995359c2003-01-26 08:59:32 +0000404 def _set_prefix(self, prefix):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000405 nsuri = self.namespaceURI
Martin v. Löwis995359c2003-01-26 08:59:32 +0000406 if prefix == "xmlns":
407 if nsuri and nsuri != XMLNS_NAMESPACE:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000408 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000409 "illegal use of 'xmlns' prefix for the wrong namespace")
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100410 self._prefix = prefix
Martin v. Löwis787354c2003-01-25 15:28:29 +0000411 if prefix is None:
412 newName = self.localName
413 else:
Martin v. Löwis995359c2003-01-26 08:59:32 +0000414 newName = "%s:%s" % (prefix, self.localName)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000415 if self.ownerElement:
416 _clear_id_cache(self.ownerElement)
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100417 self.name = newName
Martin v. Löwis787354c2003-01-25 15:28:29 +0000418
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100419 prefix = property(_get_prefix, _set_prefix)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000420
421 def unlink(self):
422 # This implementation does not call the base implementation
423 # since most of that is not needed, and the expense of the
424 # method call is not warranted. We duplicate the removal of
425 # children, but that's all we needed from the base class.
426 elem = self.ownerElement
427 if elem is not None:
428 del elem._attrs[self.nodeName]
429 del elem._attrsNS[(self.namespaceURI, self.localName)]
430 if self._is_id:
431 self._is_id = False
432 elem._magic_id_nodes -= 1
433 self.ownerDocument._magic_id_count -= 1
434 for child in self.childNodes:
435 child.unlink()
436 del self.childNodes[:]
437
438 def _get_isId(self):
439 if self._is_id:
440 return True
441 doc = self.ownerDocument
442 elem = self.ownerElement
443 if doc is None or elem is None:
444 return False
445
446 info = doc._get_elem_info(elem)
447 if info is None:
448 return False
449 if self.namespaceURI:
450 return info.isIdNS(self.namespaceURI, self.localName)
451 else:
452 return info.isId(self.nodeName)
453
454 def _get_schemaType(self):
455 doc = self.ownerDocument
456 elem = self.ownerElement
457 if doc is None or elem is None:
458 return _no_type
459
460 info = doc._get_elem_info(elem)
461 if info is None:
462 return _no_type
463 if self.namespaceURI:
464 return info.getAttributeTypeNS(self.namespaceURI, self.localName)
465 else:
466 return info.getAttributeType(self.nodeName)
467
468defproperty(Attr, "isId", doc="True if this attribute is an ID.")
469defproperty(Attr, "localName", doc="Namespace-local name of this attribute.")
470defproperty(Attr, "schemaType", doc="Schema type for this attribute.")
Fred Drake4ccf4a12000-11-21 22:02:22 +0000471
Fred Drakef7cf40d2000-12-14 18:16:11 +0000472
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000473class NamedNodeMap(object):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000474 """The attribute list is a transient interface to the underlying
475 dictionaries. Mutations here will change the underlying element's
Fred Drakef7cf40d2000-12-14 18:16:11 +0000476 dictionary.
477
478 Ordering is imposed artificially and does not reflect the order of
479 attributes as found in an input document.
480 """
Fred Drake4ccf4a12000-11-21 22:02:22 +0000481
Martin v. Löwis787354c2003-01-25 15:28:29 +0000482 __slots__ = ('_attrs', '_attrsNS', '_ownerElement')
483
Fred Drake2998a552001-12-06 18:27:48 +0000484 def __init__(self, attrs, attrsNS, ownerElement):
Fred Drake1f549022000-09-24 05:21:58 +0000485 self._attrs = attrs
486 self._attrsNS = attrsNS
Fred Drake2998a552001-12-06 18:27:48 +0000487 self._ownerElement = ownerElement
Fred Drakef7cf40d2000-12-14 18:16:11 +0000488
Martin v. Löwis787354c2003-01-25 15:28:29 +0000489 def _get_length(self):
490 return len(self._attrs)
Fred Drake55c38192000-06-29 19:39:57 +0000491
Fred Drake1f549022000-09-24 05:21:58 +0000492 def item(self, index):
Fred Drake55c38192000-06-29 19:39:57 +0000493 try:
Brett Cannon861fd6f2007-02-21 22:05:37 +0000494 return self[list(self._attrs.keys())[index]]
Fred Drake55c38192000-06-29 19:39:57 +0000495 except IndexError:
496 return None
Fred Drake55c38192000-06-29 19:39:57 +0000497
Fred Drake1f549022000-09-24 05:21:58 +0000498 def items(self):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000499 L = []
500 for node in self._attrs.values():
Martin v. Löwisd5fb58f2001-01-27 08:38:34 +0000501 L.append((node.nodeName, node.value))
Fred Drake4ccf4a12000-11-21 22:02:22 +0000502 return L
Fred Drake1f549022000-09-24 05:21:58 +0000503
504 def itemsNS(self):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000505 L = []
506 for node in self._attrs.values():
Fred Drake49a5d032001-11-30 22:21:58 +0000507 L.append(((node.namespaceURI, node.localName), node.value))
Fred Drake4ccf4a12000-11-21 22:02:22 +0000508 return L
Fred Drake16f63292000-10-23 18:09:50 +0000509
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000510 def __contains__(self, key):
Christian Heimesc9543e42007-11-28 08:28:28 +0000511 if isinstance(key, str):
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000512 return key in self._attrs
Martin v. Löwis787354c2003-01-25 15:28:29 +0000513 else:
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000514 return key in self._attrsNS
Martin v. Löwis787354c2003-01-25 15:28:29 +0000515
Fred Drake1f549022000-09-24 05:21:58 +0000516 def keys(self):
Paul Prescod73678da2000-07-01 04:58:47 +0000517 return self._attrs.keys()
Fred Drake55c38192000-06-29 19:39:57 +0000518
Fred Drake1f549022000-09-24 05:21:58 +0000519 def keysNS(self):
Paul Prescod73678da2000-07-01 04:58:47 +0000520 return self._attrsNS.keys()
Fred Drake55c38192000-06-29 19:39:57 +0000521
Fred Drake1f549022000-09-24 05:21:58 +0000522 def values(self):
Paul Prescod73678da2000-07-01 04:58:47 +0000523 return self._attrs.values()
Fred Drake55c38192000-06-29 19:39:57 +0000524
Martin v. Löwis787354c2003-01-25 15:28:29 +0000525 def get(self, name, value=None):
Martin v. Löwisd5fb58f2001-01-27 08:38:34 +0000526 return self._attrs.get(name, value)
527
Martin v. Löwis787354c2003-01-25 15:28:29 +0000528 __len__ = _get_length
Fred Drake55c38192000-06-29 19:39:57 +0000529
Mark Dickinsona56c4672009-01-27 18:17:45 +0000530 def _cmp(self, other):
Fred Drake1f549022000-09-24 05:21:58 +0000531 if self._attrs is getattr(other, "_attrs", None):
Fred Drake55c38192000-06-29 19:39:57 +0000532 return 0
Fred Drake16f63292000-10-23 18:09:50 +0000533 else:
Mark Dickinsona56c4672009-01-27 18:17:45 +0000534 return (id(self) > id(other)) - (id(self) < id(other))
535
536 def __eq__(self, other):
537 return self._cmp(other) == 0
538
539 def __ge__(self, other):
540 return self._cmp(other) >= 0
541
542 def __gt__(self, other):
543 return self._cmp(other) > 0
544
545 def __le__(self, other):
546 return self._cmp(other) <= 0
547
548 def __lt__(self, other):
549 return self._cmp(other) < 0
550
551 def __ne__(self, other):
552 return self._cmp(other) != 0
Fred Drake55c38192000-06-29 19:39:57 +0000553
Fred Drake1f549022000-09-24 05:21:58 +0000554 def __getitem__(self, attname_or_tuple):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000555 if isinstance(attname_or_tuple, tuple):
Paul Prescod73678da2000-07-01 04:58:47 +0000556 return self._attrsNS[attname_or_tuple]
Fred Drake55c38192000-06-29 19:39:57 +0000557 else:
Paul Prescod73678da2000-07-01 04:58:47 +0000558 return self._attrs[attname_or_tuple]
Fred Drake55c38192000-06-29 19:39:57 +0000559
Paul Prescod1e688272000-07-01 19:21:47 +0000560 # same as set
Fred Drake1f549022000-09-24 05:21:58 +0000561 def __setitem__(self, attname, value):
Christian Heimesc9543e42007-11-28 08:28:28 +0000562 if isinstance(value, str):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000563 try:
564 node = self._attrs[attname]
565 except KeyError:
566 node = Attr(attname)
567 node.ownerDocument = self._ownerElement.ownerDocument
Martin v. Löwis995359c2003-01-26 08:59:32 +0000568 self.setNamedItem(node)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000569 node.value = value
Paul Prescod1e688272000-07-01 19:21:47 +0000570 else:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000571 if not isinstance(value, Attr):
Collin Winter70e79802007-08-24 18:57:22 +0000572 raise TypeError("value must be a string or Attr object")
Fred Drake1f549022000-09-24 05:21:58 +0000573 node = value
Martin v. Löwis787354c2003-01-25 15:28:29 +0000574 self.setNamedItem(node)
575
576 def getNamedItem(self, name):
577 try:
578 return self._attrs[name]
579 except KeyError:
580 return None
581
582 def getNamedItemNS(self, namespaceURI, localName):
583 try:
584 return self._attrsNS[(namespaceURI, localName)]
585 except KeyError:
586 return None
587
588 def removeNamedItem(self, name):
589 n = self.getNamedItem(name)
590 if n is not None:
591 _clear_id_cache(self._ownerElement)
592 del self._attrs[n.nodeName]
593 del self._attrsNS[(n.namespaceURI, n.localName)]
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100594 if hasattr(n, 'ownerElement'):
595 n.ownerElement = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000596 return n
597 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000598 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000599
600 def removeNamedItemNS(self, namespaceURI, localName):
601 n = self.getNamedItemNS(namespaceURI, localName)
602 if n is not None:
603 _clear_id_cache(self._ownerElement)
604 del self._attrsNS[(n.namespaceURI, n.localName)]
605 del self._attrs[n.nodeName]
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100606 if hasattr(n, 'ownerElement'):
607 n.ownerElement = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000608 return n
609 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000610 raise xml.dom.NotFoundErr()
Fred Drakef7cf40d2000-12-14 18:16:11 +0000611
612 def setNamedItem(self, node):
Andrew M. Kuchlingbc8f72c2001-02-21 01:30:26 +0000613 if not isinstance(node, Attr):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000614 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000615 "%s cannot be child of %s" % (repr(node), repr(self)))
Fred Drakef7cf40d2000-12-14 18:16:11 +0000616 old = self._attrs.get(node.name)
Paul Prescod1e688272000-07-01 19:21:47 +0000617 if old:
618 old.unlink()
Fred Drake1f549022000-09-24 05:21:58 +0000619 self._attrs[node.name] = node
620 self._attrsNS[(node.namespaceURI, node.localName)] = node
Fred Drake2998a552001-12-06 18:27:48 +0000621 node.ownerElement = self._ownerElement
Martin v. Löwis787354c2003-01-25 15:28:29 +0000622 _clear_id_cache(node.ownerElement)
Fred Drakef7cf40d2000-12-14 18:16:11 +0000623 return old
624
625 def setNamedItemNS(self, node):
626 return self.setNamedItem(node)
Paul Prescod73678da2000-07-01 04:58:47 +0000627
Fred Drake1f549022000-09-24 05:21:58 +0000628 def __delitem__(self, attname_or_tuple):
629 node = self[attname_or_tuple]
Martin v. Löwis787354c2003-01-25 15:28:29 +0000630 _clear_id_cache(node.ownerElement)
Paul Prescod73678da2000-07-01 04:58:47 +0000631 node.unlink()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000632
633 def __getstate__(self):
634 return self._attrs, self._attrsNS, self._ownerElement
635
636 def __setstate__(self, state):
637 self._attrs, self._attrsNS, self._ownerElement = state
638
639defproperty(NamedNodeMap, "length",
640 doc="Number of nodes in the NamedNodeMap.")
Fred Drakef7cf40d2000-12-14 18:16:11 +0000641
642AttributeList = NamedNodeMap
643
Fred Drake1f549022000-09-24 05:21:58 +0000644
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000645class TypeInfo(object):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000646 __slots__ = 'namespace', 'name'
647
648 def __init__(self, namespace, name):
649 self.namespace = namespace
650 self.name = name
651
652 def __repr__(self):
653 if self.namespace:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000654 return "<TypeInfo %r (from %r)>" % (self.name, self.namespace)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000655 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000656 return "<TypeInfo %r>" % self.name
Martin v. Löwis787354c2003-01-25 15:28:29 +0000657
658 def _get_name(self):
659 return self.name
660
661 def _get_namespace(self):
662 return self.namespace
663
664_no_type = TypeInfo(None, None)
665
Martin v. Löwisa2fda0d2000-10-07 12:10:28 +0000666class Element(Node):
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100667 __slots__=('ownerDocument', 'parentNode', 'tagName', 'nodeName', 'prefix',
668 'namespaceURI', '_localName', 'childNodes', '_attrs', '_attrsNS',
669 'nextSibling', 'previousSibling')
Fred Drake1f549022000-09-24 05:21:58 +0000670 nodeType = Node.ELEMENT_NODE
Martin v. Löwis787354c2003-01-25 15:28:29 +0000671 nodeValue = None
672 schemaType = _no_type
673
674 _magic_id_nodes = 0
675
676 _child_node_types = (Node.ELEMENT_NODE,
677 Node.PROCESSING_INSTRUCTION_NODE,
678 Node.COMMENT_NODE,
679 Node.TEXT_NODE,
680 Node.CDATA_SECTION_NODE,
681 Node.ENTITY_REFERENCE_NODE)
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000682
Fred Drake49a5d032001-11-30 22:21:58 +0000683 def __init__(self, tagName, namespaceURI=EMPTY_NAMESPACE, prefix=None,
Fred Drake1f549022000-09-24 05:21:58 +0000684 localName=None):
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100685 self.parentNode = None
Fred Drake55c38192000-06-29 19:39:57 +0000686 self.tagName = self.nodeName = tagName
Fred Drake1f549022000-09-24 05:21:58 +0000687 self.prefix = prefix
688 self.namespaceURI = namespaceURI
Martin v. Löwis787354c2003-01-25 15:28:29 +0000689 self.childNodes = NodeList()
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100690 self.nextSibling = self.previousSibling = None
Fred Drake55c38192000-06-29 19:39:57 +0000691
Martin v. Löwis7b771882012-02-19 20:55:05 +0100692 # Attribute dictionaries are lazily created
693 # attributes are double-indexed:
694 # tagName -> Attribute
695 # URI,localName -> Attribute
696 # in the future: consider lazy generation
697 # of attribute objects this is too tricky
698 # for now because of headaches with
699 # namespaces.
700 self._attrs = None
701 self._attrsNS = None
702
703 def _ensure_attributes(self):
704 if self._attrs is None:
705 self._attrs = {}
706 self._attrsNS = {}
Fred Drake4ccf4a12000-11-21 22:02:22 +0000707
Martin v. Löwis787354c2003-01-25 15:28:29 +0000708 def _get_localName(self):
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100709 try:
710 return self._localName
711 except AttributeError:
712 return self.tagName.split(":", 1)[-1]
Martin v. Löwis787354c2003-01-25 15:28:29 +0000713
714 def _get_tagName(self):
715 return self.tagName
Fred Drake4ccf4a12000-11-21 22:02:22 +0000716
717 def unlink(self):
Martin v. Löwis7b771882012-02-19 20:55:05 +0100718 if self._attrs is not None:
719 for attr in list(self._attrs.values()):
720 attr.unlink()
Fred Drake4ccf4a12000-11-21 22:02:22 +0000721 self._attrs = None
722 self._attrsNS = None
723 Node.unlink(self)
Fred Drake55c38192000-06-29 19:39:57 +0000724
Fred Drake1f549022000-09-24 05:21:58 +0000725 def getAttribute(self, attname):
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):
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000732 try:
733 return self._attrsNS[(namespaceURI, localName)].value
734 except KeyError:
735 return ""
Fred Drake1f549022000-09-24 05:21:58 +0000736
737 def setAttribute(self, attname, value):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000738 attr = self.getAttributeNode(attname)
739 if attr is None:
740 attr = Attr(attname)
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100741 attr.value = value # also sets nodeValue
742 attr.ownerDocument = self.ownerDocument
Martin v. Löwis787354c2003-01-25 15:28:29 +0000743 self.setAttributeNode(attr)
744 elif value != attr.value:
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100745 attr.value = value
Martin v. Löwis787354c2003-01-25 15:28:29 +0000746 if attr.isId:
747 _clear_id_cache(self)
Fred Drake55c38192000-06-29 19:39:57 +0000748
Fred Drake1f549022000-09-24 05:21:58 +0000749 def setAttributeNS(self, namespaceURI, qualifiedName, value):
750 prefix, localname = _nssplit(qualifiedName)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000751 attr = self.getAttributeNodeNS(namespaceURI, localname)
752 if attr is None:
Martin v. Löwis787354c2003-01-25 15:28:29 +0000753 attr = Attr(qualifiedName, namespaceURI, localname, prefix)
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100754 attr.value = value
755 attr.ownerDocument = self.ownerDocument
Martin v. Löwis787354c2003-01-25 15:28:29 +0000756 self.setAttributeNode(attr)
757 else:
Martin v. Löwis787354c2003-01-25 15:28:29 +0000758 if value != attr.value:
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100759 attr.value = value
Martin v. Löwis787354c2003-01-25 15:28:29 +0000760 if attr.isId:
761 _clear_id_cache(self)
762 if attr.prefix != prefix:
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100763 attr.prefix = prefix
764 attr.nodeName = qualifiedName
Fred Drake55c38192000-06-29 19:39:57 +0000765
Fred Drake1f549022000-09-24 05:21:58 +0000766 def getAttributeNode(self, attrname):
Martin v. Löwis7b771882012-02-19 20:55:05 +0100767 if self._attrs is None:
768 return None
Fred Drake1f549022000-09-24 05:21:58 +0000769 return self._attrs.get(attrname)
Paul Prescod73678da2000-07-01 04:58:47 +0000770
Fred Drake1f549022000-09-24 05:21:58 +0000771 def getAttributeNodeNS(self, namespaceURI, localName):
Martin v. Löwis7b771882012-02-19 20:55:05 +0100772 if self._attrsNS is None:
773 return None
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000774 return self._attrsNS.get((namespaceURI, localName))
Paul Prescod73678da2000-07-01 04:58:47 +0000775
Fred Drake1f549022000-09-24 05:21:58 +0000776 def setAttributeNode(self, attr):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000777 if attr.ownerElement not in (None, self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000778 raise xml.dom.InuseAttributeErr("attribute node already owned")
Martin v. Löwis7b771882012-02-19 20:55:05 +0100779 self._ensure_attributes()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000780 old1 = self._attrs.get(attr.name, None)
781 if old1 is not None:
782 self.removeAttributeNode(old1)
783 old2 = self._attrsNS.get((attr.namespaceURI, attr.localName), None)
784 if old2 is not None and old2 is not old1:
785 self.removeAttributeNode(old2)
786 _set_attribute_node(self, attr)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000787
Martin v. Löwis787354c2003-01-25 15:28:29 +0000788 if old1 is not attr:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000789 # It might have already been part of this node, in which case
790 # it doesn't represent a change, and should not be returned.
Martin v. Löwis787354c2003-01-25 15:28:29 +0000791 return old1
792 if old2 is not attr:
793 return old2
Fred Drake55c38192000-06-29 19:39:57 +0000794
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000795 setAttributeNodeNS = setAttributeNode
796
Fred Drake1f549022000-09-24 05:21:58 +0000797 def removeAttribute(self, name):
Martin v. Löwis7b771882012-02-19 20:55:05 +0100798 if self._attrsNS is None:
799 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000800 try:
801 attr = self._attrs[name]
802 except KeyError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000803 raise xml.dom.NotFoundErr()
Fred Drake1f549022000-09-24 05:21:58 +0000804 self.removeAttributeNode(attr)
Fred Drake55c38192000-06-29 19:39:57 +0000805
Fred Drake1f549022000-09-24 05:21:58 +0000806 def removeAttributeNS(self, namespaceURI, localName):
Martin v. Löwis7b771882012-02-19 20:55:05 +0100807 if self._attrsNS is None:
808 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000809 try:
810 attr = self._attrsNS[(namespaceURI, localName)]
811 except KeyError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000812 raise xml.dom.NotFoundErr()
Fred Drake1f549022000-09-24 05:21:58 +0000813 self.removeAttributeNode(attr)
Fred Drake55c38192000-06-29 19:39:57 +0000814
Fred Drake1f549022000-09-24 05:21:58 +0000815 def removeAttributeNode(self, node):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000816 if node is None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000817 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000818 try:
819 self._attrs[node.name]
820 except KeyError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000821 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000822 _clear_id_cache(self)
Paul Prescod73678da2000-07-01 04:58:47 +0000823 node.unlink()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000824 # Restore this since the node is still useful and otherwise
825 # unlinked
826 node.ownerDocument = self.ownerDocument
Fred Drake16f63292000-10-23 18:09:50 +0000827
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000828 removeAttributeNodeNS = removeAttributeNode
829
Martin v. Löwis156c3372000-12-28 18:40:56 +0000830 def hasAttribute(self, name):
Martin v. Löwis7b771882012-02-19 20:55:05 +0100831 if self._attrs is None:
832 return False
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000833 return name in self._attrs
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000834
Martin v. Löwis156c3372000-12-28 18:40:56 +0000835 def hasAttributeNS(self, namespaceURI, localName):
Martin v. Löwis7b771882012-02-19 20:55:05 +0100836 if self._attrsNS is None:
837 return False
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000838 return (namespaceURI, localName) in self._attrsNS
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000839
Fred Drake1f549022000-09-24 05:21:58 +0000840 def getElementsByTagName(self, name):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000841 return _get_elements_by_tagName_helper(self, name, NodeList())
Fred Drake55c38192000-06-29 19:39:57 +0000842
Fred Drake1f549022000-09-24 05:21:58 +0000843 def getElementsByTagNameNS(self, namespaceURI, localName):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000844 return _get_elements_by_tagName_ns_helper(
845 self, namespaceURI, localName, NodeList())
Fred Drake55c38192000-06-29 19:39:57 +0000846
Fred Drake1f549022000-09-24 05:21:58 +0000847 def __repr__(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000848 return "<DOM Element: %s at %#x>" % (self.tagName, id(self))
Fred Drake55c38192000-06-29 19:39:57 +0000849
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000850 def writexml(self, writer, indent="", addindent="", newl=""):
851 # indent = current indentation
852 # addindent = indentation to add to higher levels
853 # newl = newline string
854 writer.write(indent+"<" + self.tagName)
Fred Drake16f63292000-10-23 18:09:50 +0000855
Fred Drake4ccf4a12000-11-21 22:02:22 +0000856 attrs = self._get_attributes()
Brett Cannon861fd6f2007-02-21 22:05:37 +0000857 a_names = sorted(attrs.keys())
Fred Drake55c38192000-06-29 19:39:57 +0000858
859 for a_name in a_names:
Fred Drake1f549022000-09-24 05:21:58 +0000860 writer.write(" %s=\"" % a_name)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000861 _write_data(writer, attrs[a_name].value)
Fred Drake55c38192000-06-29 19:39:57 +0000862 writer.write("\"")
863 if self.childNodes:
R David Murray791744b2011-10-01 16:19:51 -0400864 writer.write(">")
Ezio Melotti8008f2a2011-11-18 17:34:26 +0200865 if (len(self.childNodes) == 1 and
866 self.childNodes[0].nodeType == Node.TEXT_NODE):
867 self.childNodes[0].writexml(writer, '', '', '')
868 else:
R David Murray791744b2011-10-01 16:19:51 -0400869 writer.write(newl)
Ezio Melotti8008f2a2011-11-18 17:34:26 +0200870 for node in self.childNodes:
871 node.writexml(writer, indent+addindent, addindent, newl)
872 writer.write(indent)
873 writer.write("</%s>%s" % (self.tagName, newl))
Fred Drake55c38192000-06-29 19:39:57 +0000874 else:
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000875 writer.write("/>%s"%(newl))
Fred Drake55c38192000-06-29 19:39:57 +0000876
Fred Drake1f549022000-09-24 05:21:58 +0000877 def _get_attributes(self):
Martin v. Löwis7b771882012-02-19 20:55:05 +0100878 self._ensure_attributes()
Fred Drake2998a552001-12-06 18:27:48 +0000879 return NamedNodeMap(self._attrs, self._attrsNS, self)
Fred Drake55c38192000-06-29 19:39:57 +0000880
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000881 def hasAttributes(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000882 if self._attrs:
883 return True
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000884 else:
Martin v. Löwis787354c2003-01-25 15:28:29 +0000885 return False
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000886
Martin v. Löwis787354c2003-01-25 15:28:29 +0000887 # DOM Level 3 attributes, based on the 22 Oct 2002 draft
888
889 def setIdAttribute(self, name):
890 idAttr = self.getAttributeNode(name)
891 self.setIdAttributeNode(idAttr)
892
893 def setIdAttributeNS(self, namespaceURI, localName):
894 idAttr = self.getAttributeNodeNS(namespaceURI, localName)
895 self.setIdAttributeNode(idAttr)
896
897 def setIdAttributeNode(self, idAttr):
898 if idAttr is None or not self.isSameNode(idAttr.ownerElement):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000899 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000900 if _get_containing_entref(self) is not None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000901 raise xml.dom.NoModificationAllowedErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000902 if not idAttr._is_id:
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100903 idAttr._is_id = True
Martin v. Löwis787354c2003-01-25 15:28:29 +0000904 self._magic_id_nodes += 1
905 self.ownerDocument._magic_id_count += 1
906 _clear_id_cache(self)
907
908defproperty(Element, "attributes",
909 doc="NamedNodeMap of attributes on the element.")
910defproperty(Element, "localName",
911 doc="Namespace-local name of this element.")
912
913
914def _set_attribute_node(element, attr):
915 _clear_id_cache(element)
Martin v. Löwis7b771882012-02-19 20:55:05 +0100916 element._ensure_attributes()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000917 element._attrs[attr.name] = attr
918 element._attrsNS[(attr.namespaceURI, attr.localName)] = attr
919
920 # This creates a circular reference, but Element.unlink()
921 # breaks the cycle since the references to the attribute
922 # dictionaries are tossed.
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100923 attr.ownerElement = element
Martin v. Löwis787354c2003-01-25 15:28:29 +0000924
925class Childless:
926 """Mixin that makes childless-ness easy to implement and avoids
927 the complexity of the Node methods that deal with children.
928 """
929
Fred Drake4ccf4a12000-11-21 22:02:22 +0000930 attributes = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000931 childNodes = EmptyNodeList()
932 firstChild = None
933 lastChild = None
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000934
Martin v. Löwis787354c2003-01-25 15:28:29 +0000935 def _get_firstChild(self):
936 return None
Fred Drake55c38192000-06-29 19:39:57 +0000937
Martin v. Löwis787354c2003-01-25 15:28:29 +0000938 def _get_lastChild(self):
939 return None
Fred Drake1f549022000-09-24 05:21:58 +0000940
Martin v. Löwis787354c2003-01-25 15:28:29 +0000941 def appendChild(self, node):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000942 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000943 self.nodeName + " nodes cannot have children")
944
945 def hasChildNodes(self):
946 return False
947
948 def insertBefore(self, newChild, refChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000949 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000950 self.nodeName + " nodes do not have children")
951
952 def removeChild(self, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000953 raise xml.dom.NotFoundErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000954 self.nodeName + " nodes do not have children")
955
Andrew M. Kuchling688b9e32010-07-25 23:38:47 +0000956 def normalize(self):
957 # For childless nodes, normalize() has nothing to do.
958 pass
959
Martin v. Löwis787354c2003-01-25 15:28:29 +0000960 def replaceChild(self, newChild, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000961 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000962 self.nodeName + " nodes do not have children")
963
964
965class ProcessingInstruction(Childless, Node):
Fred Drake1f549022000-09-24 05:21:58 +0000966 nodeType = Node.PROCESSING_INSTRUCTION_NODE
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100967 __slots__ = ('target', 'data')
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000968
Fred Drake1f549022000-09-24 05:21:58 +0000969 def __init__(self, target, data):
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100970 self.target = target
971 self.data = data
Fred Drake55c38192000-06-29 19:39:57 +0000972
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100973 # nodeValue is an alias for data
974 def _get_nodeValue(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000975 return self.data
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100976 def _set_nodeValue(self, value):
977 self.data = data
978 nodeValue = property(_get_nodeValue, _set_nodeValue)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000979
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100980 # nodeName is an alias for target
981 def _get_nodeName(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000982 return self.target
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100983 def _set_nodeName(self, value):
984 self.target = value
985 nodeName = property(_get_nodeName, _set_nodeName)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000986
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000987 def writexml(self, writer, indent="", addindent="", newl=""):
988 writer.write("%s<?%s %s?>%s" % (indent,self.target, self.data, newl))
Fred Drake55c38192000-06-29 19:39:57 +0000989
Martin v. Löwis787354c2003-01-25 15:28:29 +0000990
991class CharacterData(Childless, Node):
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100992 __slots__=('_data', 'ownerDocument','parentNode', 'previousSibling', 'nextSibling')
993
994 def __init__(self):
995 self.ownerDocument = self.parentNode = None
996 self.previousSibling = self.nextSibling = None
997 self._data = ''
998 Node.__init__(self)
999
Martin v. Löwis787354c2003-01-25 15:28:29 +00001000 def _get_length(self):
1001 return len(self.data)
1002 __len__ = _get_length
1003
1004 def _get_data(self):
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001005 return self._data
Martin v. Löwis787354c2003-01-25 15:28:29 +00001006 def _set_data(self, data):
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001007 self._data = data
Martin v. Löwis787354c2003-01-25 15:28:29 +00001008
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001009 data = nodeValue = property(_get_data, _set_data)
Fred Drake87432f42001-04-04 14:09:46 +00001010
Fred Drake55c38192000-06-29 19:39:57 +00001011 def __repr__(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001012 data = self.data
1013 if len(data) > 10:
Fred Drake1f549022000-09-24 05:21:58 +00001014 dotdotdot = "..."
Fred Drake55c38192000-06-29 19:39:57 +00001015 else:
Fred Drake1f549022000-09-24 05:21:58 +00001016 dotdotdot = ""
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001017 return '<DOM %s node "%r%s">' % (
Martin v. Löwis787354c2003-01-25 15:28:29 +00001018 self.__class__.__name__, data[0:10], dotdotdot)
Fred Drake87432f42001-04-04 14:09:46 +00001019
1020 def substringData(self, offset, count):
1021 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001022 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001023 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001024 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +00001025 if count < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001026 raise xml.dom.IndexSizeErr("count cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001027 return self.data[offset:offset+count]
1028
1029 def appendData(self, arg):
1030 self.data = self.data + arg
Fred Drake87432f42001-04-04 14:09:46 +00001031
1032 def insertData(self, offset, arg):
1033 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001034 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001035 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001036 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +00001037 if arg:
1038 self.data = "%s%s%s" % (
1039 self.data[:offset], arg, self.data[offset:])
Fred Drake87432f42001-04-04 14:09:46 +00001040
1041 def deleteData(self, offset, count):
1042 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001043 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001044 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001045 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +00001046 if count < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001047 raise xml.dom.IndexSizeErr("count cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001048 if count:
1049 self.data = self.data[:offset] + self.data[offset+count:]
Fred Drake87432f42001-04-04 14:09:46 +00001050
1051 def replaceData(self, offset, count, arg):
1052 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001053 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001054 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001055 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +00001056 if count < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001057 raise xml.dom.IndexSizeErr("count cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001058 if count:
1059 self.data = "%s%s%s" % (
1060 self.data[:offset], arg, self.data[offset+count:])
Martin v. Löwis787354c2003-01-25 15:28:29 +00001061
1062defproperty(CharacterData, "length", doc="Length of the string data.")
1063
Fred Drake87432f42001-04-04 14:09:46 +00001064
1065class Text(CharacterData):
1066 nodeType = Node.TEXT_NODE
1067 nodeName = "#text"
1068 attributes = None
Fred Drake55c38192000-06-29 19:39:57 +00001069
Fred Drakef7cf40d2000-12-14 18:16:11 +00001070 def splitText(self, offset):
1071 if offset < 0 or offset > len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001072 raise xml.dom.IndexSizeErr("illegal offset value")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001073 newText = self.__class__()
1074 newText.data = self.data[offset:]
1075 newText.ownerDocument = self.ownerDocument
Fred Drakef7cf40d2000-12-14 18:16:11 +00001076 next = self.nextSibling
1077 if self.parentNode and self in self.parentNode.childNodes:
1078 if next is None:
1079 self.parentNode.appendChild(newText)
1080 else:
1081 self.parentNode.insertBefore(newText, next)
1082 self.data = self.data[:offset]
1083 return newText
1084
Martin v. Löwis46fa39a2001-02-06 00:14:08 +00001085 def writexml(self, writer, indent="", addindent="", newl=""):
Ezio Melotti8008f2a2011-11-18 17:34:26 +02001086 _write_data(writer, "%s%s%s" % (indent, self.data, newl))
Fred Drake55c38192000-06-29 19:39:57 +00001087
Martin v. Löwis787354c2003-01-25 15:28:29 +00001088 # DOM Level 3 (WD 9 April 2002)
1089
1090 def _get_wholeText(self):
1091 L = [self.data]
1092 n = self.previousSibling
1093 while n is not None:
1094 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1095 L.insert(0, n.data)
1096 n = n.previousSibling
1097 else:
1098 break
1099 n = self.nextSibling
1100 while n is not None:
1101 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1102 L.append(n.data)
1103 n = n.nextSibling
1104 else:
1105 break
1106 return ''.join(L)
1107
1108 def replaceWholeText(self, content):
1109 # XXX This needs to be seriously changed if minidom ever
1110 # supports EntityReference nodes.
1111 parent = self.parentNode
1112 n = self.previousSibling
1113 while n is not None:
1114 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1115 next = n.previousSibling
1116 parent.removeChild(n)
1117 n = next
1118 else:
1119 break
1120 n = self.nextSibling
1121 if not content:
1122 parent.removeChild(self)
1123 while n is not None:
1124 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1125 next = n.nextSibling
1126 parent.removeChild(n)
1127 n = next
1128 else:
1129 break
1130 if content:
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001131 self.data = content
Martin v. Löwis787354c2003-01-25 15:28:29 +00001132 return self
1133 else:
1134 return None
1135
1136 def _get_isWhitespaceInElementContent(self):
1137 if self.data.strip():
1138 return False
1139 elem = _get_containing_element(self)
1140 if elem is None:
1141 return False
1142 info = self.ownerDocument._get_elem_info(elem)
1143 if info is None:
1144 return False
1145 else:
1146 return info.isElementContent()
1147
1148defproperty(Text, "isWhitespaceInElementContent",
1149 doc="True iff this text node contains only whitespace"
1150 " and is in element content.")
1151defproperty(Text, "wholeText",
1152 doc="The text of all logically-adjacent text nodes.")
1153
1154
1155def _get_containing_element(node):
1156 c = node.parentNode
1157 while c is not None:
1158 if c.nodeType == Node.ELEMENT_NODE:
1159 return c
1160 c = c.parentNode
1161 return None
1162
1163def _get_containing_entref(node):
1164 c = node.parentNode
1165 while c is not None:
1166 if c.nodeType == Node.ENTITY_REFERENCE_NODE:
1167 return c
1168 c = c.parentNode
1169 return None
1170
1171
Alex Martelli0ee43512006-08-21 19:53:20 +00001172class Comment(CharacterData):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001173 nodeType = Node.COMMENT_NODE
1174 nodeName = "#comment"
1175
1176 def __init__(self, data):
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001177 CharacterData.__init__(self)
1178 self._data = data
Martin v. Löwis787354c2003-01-25 15:28:29 +00001179
1180 def writexml(self, writer, indent="", addindent="", newl=""):
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001181 if "--" in self.data:
1182 raise ValueError("'--' is not allowed in a comment node")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001183 writer.write("%s<!--%s-->%s" % (indent, self.data, newl))
1184
Fred Drake87432f42001-04-04 14:09:46 +00001185
1186class CDATASection(Text):
1187 nodeType = Node.CDATA_SECTION_NODE
1188 nodeName = "#cdata-section"
1189
1190 def writexml(self, writer, indent="", addindent="", newl=""):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001191 if self.data.find("]]>") >= 0:
1192 raise ValueError("']]>' not allowed in a CDATA section")
Guido van Rossum5b5e0b92001-09-19 13:28:25 +00001193 writer.write("<![CDATA[%s]]>" % self.data)
Fred Drake87432f42001-04-04 14:09:46 +00001194
1195
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001196class ReadOnlySequentialNamedNodeMap(object):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001197 __slots__ = '_seq',
1198
1199 def __init__(self, seq=()):
1200 # seq should be a list or tuple
1201 self._seq = seq
1202
1203 def __len__(self):
1204 return len(self._seq)
1205
1206 def _get_length(self):
1207 return len(self._seq)
1208
1209 def getNamedItem(self, name):
1210 for n in self._seq:
1211 if n.nodeName == name:
1212 return n
1213
1214 def getNamedItemNS(self, namespaceURI, localName):
1215 for n in self._seq:
1216 if n.namespaceURI == namespaceURI and n.localName == localName:
1217 return n
1218
1219 def __getitem__(self, name_or_tuple):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001220 if isinstance(name_or_tuple, tuple):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001221 node = self.getNamedItemNS(*name_or_tuple)
1222 else:
1223 node = self.getNamedItem(name_or_tuple)
1224 if node is None:
Collin Winter70e79802007-08-24 18:57:22 +00001225 raise KeyError(name_or_tuple)
Martin v. Löwis787354c2003-01-25 15:28:29 +00001226 return node
1227
1228 def item(self, index):
1229 if index < 0:
1230 return None
1231 try:
1232 return self._seq[index]
1233 except IndexError:
1234 return None
1235
1236 def removeNamedItem(self, name):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001237 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001238 "NamedNodeMap instance is read-only")
1239
1240 def removeNamedItemNS(self, namespaceURI, localName):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001241 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001242 "NamedNodeMap instance is read-only")
1243
1244 def setNamedItem(self, node):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001245 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001246 "NamedNodeMap instance is read-only")
1247
1248 def setNamedItemNS(self, node):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001249 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001250 "NamedNodeMap instance is read-only")
1251
1252 def __getstate__(self):
1253 return [self._seq]
1254
1255 def __setstate__(self, state):
1256 self._seq = state[0]
1257
1258defproperty(ReadOnlySequentialNamedNodeMap, "length",
1259 doc="Number of entries in the NamedNodeMap.")
Paul Prescod73678da2000-07-01 04:58:47 +00001260
Fred Drakef7cf40d2000-12-14 18:16:11 +00001261
Martin v. Löwis787354c2003-01-25 15:28:29 +00001262class Identified:
1263 """Mix-in class that supports the publicId and systemId attributes."""
1264
Martin v. Löwis995359c2003-01-26 08:59:32 +00001265 # XXX this does not work, this is an old-style class
1266 # __slots__ = 'publicId', 'systemId'
Martin v. Löwis787354c2003-01-25 15:28:29 +00001267
1268 def _identified_mixin_init(self, publicId, systemId):
1269 self.publicId = publicId
1270 self.systemId = systemId
1271
1272 def _get_publicId(self):
1273 return self.publicId
1274
1275 def _get_systemId(self):
1276 return self.systemId
1277
1278class DocumentType(Identified, Childless, Node):
Fred Drakef7cf40d2000-12-14 18:16:11 +00001279 nodeType = Node.DOCUMENT_TYPE_NODE
1280 nodeValue = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001281 name = None
1282 publicId = None
1283 systemId = None
Fred Drakedc806702001-04-05 14:41:30 +00001284 internalSubset = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001285
1286 def __init__(self, qualifiedName):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001287 self.entities = ReadOnlySequentialNamedNodeMap()
1288 self.notations = ReadOnlySequentialNamedNodeMap()
Fred Drakef7cf40d2000-12-14 18:16:11 +00001289 if qualifiedName:
1290 prefix, localname = _nssplit(qualifiedName)
1291 self.name = localname
Martin v. Löwis787354c2003-01-25 15:28:29 +00001292 self.nodeName = self.name
1293
1294 def _get_internalSubset(self):
1295 return self.internalSubset
1296
1297 def cloneNode(self, deep):
1298 if self.ownerDocument is None:
1299 # it's ok
1300 clone = DocumentType(None)
1301 clone.name = self.name
1302 clone.nodeName = self.name
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001303 operation = xml.dom.UserDataHandler.NODE_CLONED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001304 if deep:
1305 clone.entities._seq = []
1306 clone.notations._seq = []
1307 for n in self.notations._seq:
1308 notation = Notation(n.nodeName, n.publicId, n.systemId)
1309 clone.notations._seq.append(notation)
1310 n._call_user_data_handler(operation, n, notation)
1311 for e in self.entities._seq:
1312 entity = Entity(e.nodeName, e.publicId, e.systemId,
1313 e.notationName)
1314 entity.actualEncoding = e.actualEncoding
1315 entity.encoding = e.encoding
1316 entity.version = e.version
1317 clone.entities._seq.append(entity)
1318 e._call_user_data_handler(operation, n, entity)
1319 self._call_user_data_handler(operation, self, clone)
1320 return clone
1321 else:
1322 return None
1323
1324 def writexml(self, writer, indent="", addindent="", newl=""):
1325 writer.write("<!DOCTYPE ")
1326 writer.write(self.name)
1327 if self.publicId:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001328 writer.write("%s PUBLIC '%s'%s '%s'"
1329 % (newl, self.publicId, newl, self.systemId))
Martin v. Löwis787354c2003-01-25 15:28:29 +00001330 elif self.systemId:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001331 writer.write("%s SYSTEM '%s'" % (newl, self.systemId))
Martin v. Löwis787354c2003-01-25 15:28:29 +00001332 if self.internalSubset is not None:
1333 writer.write(" [")
1334 writer.write(self.internalSubset)
1335 writer.write("]")
Georg Brandl175a7dc2005-08-25 22:02:43 +00001336 writer.write(">"+newl)
Martin v. Löwis787354c2003-01-25 15:28:29 +00001337
1338class Entity(Identified, Node):
1339 attributes = None
1340 nodeType = Node.ENTITY_NODE
1341 nodeValue = None
1342
1343 actualEncoding = None
1344 encoding = None
1345 version = None
1346
1347 def __init__(self, name, publicId, systemId, notation):
1348 self.nodeName = name
1349 self.notationName = notation
1350 self.childNodes = NodeList()
1351 self._identified_mixin_init(publicId, systemId)
1352
1353 def _get_actualEncoding(self):
1354 return self.actualEncoding
1355
1356 def _get_encoding(self):
1357 return self.encoding
1358
1359 def _get_version(self):
1360 return self.version
1361
1362 def appendChild(self, newChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001363 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001364 "cannot append children to an entity node")
1365
1366 def insertBefore(self, newChild, refChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001367 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001368 "cannot insert children below an entity node")
1369
1370 def removeChild(self, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001371 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001372 "cannot remove children from an entity node")
1373
1374 def replaceChild(self, newChild, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001375 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001376 "cannot replace children of an entity node")
1377
1378class Notation(Identified, Childless, Node):
1379 nodeType = Node.NOTATION_NODE
1380 nodeValue = None
1381
1382 def __init__(self, name, publicId, systemId):
1383 self.nodeName = name
1384 self._identified_mixin_init(publicId, systemId)
Fred Drakef7cf40d2000-12-14 18:16:11 +00001385
1386
Martin v. Löwis787354c2003-01-25 15:28:29 +00001387class DOMImplementation(DOMImplementationLS):
1388 _features = [("core", "1.0"),
1389 ("core", "2.0"),
Martin v. Löwis787354c2003-01-25 15:28:29 +00001390 ("core", None),
1391 ("xml", "1.0"),
1392 ("xml", "2.0"),
Martin v. Löwis787354c2003-01-25 15:28:29 +00001393 ("xml", None),
1394 ("ls-load", "3.0"),
1395 ("ls-load", None),
1396 ]
1397
Fred Drakef7cf40d2000-12-14 18:16:11 +00001398 def hasFeature(self, feature, version):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001399 if version == "":
1400 version = None
1401 return (feature.lower(), version) in self._features
Fred Drakef7cf40d2000-12-14 18:16:11 +00001402
1403 def createDocument(self, namespaceURI, qualifiedName, doctype):
1404 if doctype and doctype.parentNode is not None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001405 raise xml.dom.WrongDocumentErr(
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +00001406 "doctype object owned by another DOM tree")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001407 doc = self._create_document()
1408
1409 add_root_element = not (namespaceURI is None
1410 and qualifiedName is None
1411 and doctype is None)
1412
1413 if not qualifiedName and add_root_element:
Martin v. Löwisb417be22001-02-06 01:16:06 +00001414 # The spec is unclear what to raise here; SyntaxErr
1415 # would be the other obvious candidate. Since Xerces raises
1416 # InvalidCharacterErr, and since SyntaxErr is not listed
1417 # for createDocument, that seems to be the better choice.
1418 # XXX: need to check for illegal characters here and in
1419 # createElement.
Martin v. Löwis787354c2003-01-25 15:28:29 +00001420
1421 # DOM Level III clears this up when talking about the return value
1422 # of this function. If namespaceURI, qName and DocType are
1423 # Null the document is returned without a document element
1424 # Otherwise if doctype or namespaceURI are not None
1425 # Then we go back to the above problem
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001426 raise xml.dom.InvalidCharacterErr("Element with no name")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001427
1428 if add_root_element:
1429 prefix, localname = _nssplit(qualifiedName)
1430 if prefix == "xml" \
1431 and namespaceURI != "http://www.w3.org/XML/1998/namespace":
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001432 raise xml.dom.NamespaceErr("illegal use of 'xml' prefix")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001433 if prefix and not namespaceURI:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001434 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001435 "illegal use of prefix without namespaces")
1436 element = doc.createElementNS(namespaceURI, qualifiedName)
1437 if doctype:
1438 doc.appendChild(doctype)
1439 doc.appendChild(element)
1440
1441 if doctype:
1442 doctype.parentNode = doctype.ownerDocument = doc
1443
Fred Drakef7cf40d2000-12-14 18:16:11 +00001444 doc.doctype = doctype
1445 doc.implementation = self
1446 return doc
1447
1448 def createDocumentType(self, qualifiedName, publicId, systemId):
1449 doctype = DocumentType(qualifiedName)
1450 doctype.publicId = publicId
1451 doctype.systemId = systemId
1452 return doctype
1453
Martin v. Löwis787354c2003-01-25 15:28:29 +00001454 # DOM Level 3 (WD 9 April 2002)
1455
1456 def getInterface(self, feature):
1457 if self.hasFeature(feature, None):
1458 return self
1459 else:
1460 return None
1461
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001462 # internal
Martin v. Löwis787354c2003-01-25 15:28:29 +00001463 def _create_document(self):
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001464 return Document()
Fred Drakef7cf40d2000-12-14 18:16:11 +00001465
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001466class ElementInfo(object):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001467 """Object that represents content-model information for an element.
1468
1469 This implementation is not expected to be used in practice; DOM
1470 builders should provide implementations which do the right thing
1471 using information available to it.
1472
1473 """
1474
1475 __slots__ = 'tagName',
1476
1477 def __init__(self, name):
1478 self.tagName = name
1479
1480 def getAttributeType(self, aname):
1481 return _no_type
1482
1483 def getAttributeTypeNS(self, namespaceURI, localName):
1484 return _no_type
1485
1486 def isElementContent(self):
1487 return False
1488
1489 def isEmpty(self):
1490 """Returns true iff this element is declared to have an EMPTY
1491 content model."""
1492 return False
1493
1494 def isId(self, aname):
Ezio Melotti42da6632011-03-15 05:18:48 +02001495 """Returns true iff the named attribute is a DTD-style ID."""
Martin v. Löwis787354c2003-01-25 15:28:29 +00001496 return False
1497
1498 def isIdNS(self, namespaceURI, localName):
1499 """Returns true iff the identified attribute is a DTD-style ID."""
1500 return False
1501
1502 def __getstate__(self):
1503 return self.tagName
1504
1505 def __setstate__(self, state):
1506 self.tagName = state
1507
1508def _clear_id_cache(node):
1509 if node.nodeType == Node.DOCUMENT_NODE:
1510 node._id_cache.clear()
1511 node._id_search_stack = None
1512 elif _in_document(node):
1513 node.ownerDocument._id_cache.clear()
1514 node.ownerDocument._id_search_stack= None
1515
1516class Document(Node, DocumentLS):
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001517 __slots__ = ('_elem_info', 'doctype',
1518 '_id_search_stack', 'childNodes', '_id_cache')
Martin v. Löwis787354c2003-01-25 15:28:29 +00001519 _child_node_types = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE,
1520 Node.COMMENT_NODE, Node.DOCUMENT_TYPE_NODE)
1521
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001522 implementation = DOMImplementation()
Fred Drake1f549022000-09-24 05:21:58 +00001523 nodeType = Node.DOCUMENT_NODE
Fred Drake4ccf4a12000-11-21 22:02:22 +00001524 nodeName = "#document"
1525 nodeValue = None
1526 attributes = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001527 parentNode = None
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001528 previousSibling = nextSibling = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001529
Martin v. Löwis787354c2003-01-25 15:28:29 +00001530
1531 # Document attributes from Level 3 (WD 9 April 2002)
1532
1533 actualEncoding = None
1534 encoding = None
1535 standalone = None
1536 version = None
1537 strictErrorChecking = False
1538 errorHandler = None
1539 documentURI = None
1540
1541 _magic_id_count = 0
1542
1543 def __init__(self):
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001544 self.doctype = None
Martin v. Löwis787354c2003-01-25 15:28:29 +00001545 self.childNodes = NodeList()
1546 # mapping of (namespaceURI, localName) -> ElementInfo
1547 # and tagName -> ElementInfo
1548 self._elem_info = {}
1549 self._id_cache = {}
1550 self._id_search_stack = None
1551
1552 def _get_elem_info(self, element):
1553 if element.namespaceURI:
1554 key = element.namespaceURI, element.localName
1555 else:
1556 key = element.tagName
1557 return self._elem_info.get(key)
1558
1559 def _get_actualEncoding(self):
1560 return self.actualEncoding
1561
1562 def _get_doctype(self):
1563 return self.doctype
1564
1565 def _get_documentURI(self):
1566 return self.documentURI
1567
1568 def _get_encoding(self):
1569 return self.encoding
1570
1571 def _get_errorHandler(self):
1572 return self.errorHandler
1573
1574 def _get_standalone(self):
1575 return self.standalone
1576
1577 def _get_strictErrorChecking(self):
1578 return self.strictErrorChecking
1579
1580 def _get_version(self):
1581 return self.version
Fred Drake55c38192000-06-29 19:39:57 +00001582
Fred Drake1f549022000-09-24 05:21:58 +00001583 def appendChild(self, node):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001584 if node.nodeType not in self._child_node_types:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001585 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001586 "%s cannot be child of %s" % (repr(node), repr(self)))
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001587 if node.parentNode is not None:
Martin v. Löwis787354c2003-01-25 15:28:29 +00001588 # This needs to be done before the next test since this
1589 # may *be* the document element, in which case it should
1590 # end up re-ordered to the end.
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001591 node.parentNode.removeChild(node)
1592
Fred Drakef7cf40d2000-12-14 18:16:11 +00001593 if node.nodeType == Node.ELEMENT_NODE \
1594 and self._get_documentElement():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001595 raise xml.dom.HierarchyRequestErr(
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +00001596 "two document elements disallowed")
Fred Drake4ccf4a12000-11-21 22:02:22 +00001597 return Node.appendChild(self, node)
Paul Prescod73678da2000-07-01 04:58:47 +00001598
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001599 def removeChild(self, oldChild):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001600 try:
1601 self.childNodes.remove(oldChild)
1602 except ValueError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001603 raise xml.dom.NotFoundErr()
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001604 oldChild.nextSibling = oldChild.previousSibling = None
1605 oldChild.parentNode = None
1606 if self.documentElement is oldChild:
1607 self.documentElement = None
Martin v. Löwis52ce0d02001-01-27 08:47:37 +00001608
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001609 return oldChild
1610
Fred Drakef7cf40d2000-12-14 18:16:11 +00001611 def _get_documentElement(self):
1612 for node in self.childNodes:
1613 if node.nodeType == Node.ELEMENT_NODE:
1614 return node
1615
1616 def unlink(self):
1617 if self.doctype is not None:
1618 self.doctype.unlink()
1619 self.doctype = None
1620 Node.unlink(self)
1621
Martin v. Löwis787354c2003-01-25 15:28:29 +00001622 def cloneNode(self, deep):
1623 if not deep:
1624 return None
1625 clone = self.implementation.createDocument(None, None, None)
1626 clone.encoding = self.encoding
1627 clone.standalone = self.standalone
1628 clone.version = self.version
1629 for n in self.childNodes:
1630 childclone = _clone_node(n, deep, clone)
1631 assert childclone.ownerDocument.isSameNode(clone)
1632 clone.childNodes.append(childclone)
1633 if childclone.nodeType == Node.DOCUMENT_NODE:
1634 assert clone.documentElement is None
1635 elif childclone.nodeType == Node.DOCUMENT_TYPE_NODE:
1636 assert clone.doctype is None
1637 clone.doctype = childclone
1638 childclone.parentNode = clone
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001639 self._call_user_data_handler(xml.dom.UserDataHandler.NODE_CLONED,
Martin v. Löwis787354c2003-01-25 15:28:29 +00001640 self, clone)
1641 return clone
1642
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001643 def createDocumentFragment(self):
1644 d = DocumentFragment()
Martin v. Löwis787354c2003-01-25 15:28:29 +00001645 d.ownerDocument = self
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001646 return d
Fred Drake55c38192000-06-29 19:39:57 +00001647
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001648 def createElement(self, tagName):
1649 e = Element(tagName)
1650 e.ownerDocument = self
1651 return e
Fred Drake55c38192000-06-29 19:39:57 +00001652
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001653 def createTextNode(self, data):
Christian Heimesc9543e42007-11-28 08:28:28 +00001654 if not isinstance(data, str):
Collin Winter70e79802007-08-24 18:57:22 +00001655 raise TypeError("node contents must be a string")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001656 t = Text()
1657 t.data = data
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001658 t.ownerDocument = self
1659 return t
Fred Drake55c38192000-06-29 19:39:57 +00001660
Fred Drake87432f42001-04-04 14:09:46 +00001661 def createCDATASection(self, data):
Christian Heimesc9543e42007-11-28 08:28:28 +00001662 if not isinstance(data, str):
Collin Winter70e79802007-08-24 18:57:22 +00001663 raise TypeError("node contents must be a string")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001664 c = CDATASection()
1665 c.data = data
Fred Drake87432f42001-04-04 14:09:46 +00001666 c.ownerDocument = self
1667 return c
1668
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001669 def createComment(self, data):
1670 c = Comment(data)
1671 c.ownerDocument = self
1672 return c
Fred Drake55c38192000-06-29 19:39:57 +00001673
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001674 def createProcessingInstruction(self, target, data):
1675 p = ProcessingInstruction(target, data)
1676 p.ownerDocument = self
1677 return p
1678
1679 def createAttribute(self, qName):
1680 a = Attr(qName)
1681 a.ownerDocument = self
Martin v. Löwiscb67ea12001-03-31 16:30:40 +00001682 a.value = ""
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001683 return a
Fred Drake55c38192000-06-29 19:39:57 +00001684
1685 def createElementNS(self, namespaceURI, qualifiedName):
Fred Drake4ccf4a12000-11-21 22:02:22 +00001686 prefix, localName = _nssplit(qualifiedName)
Martin v. Löwis787354c2003-01-25 15:28:29 +00001687 e = Element(qualifiedName, namespaceURI, prefix)
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001688 e.ownerDocument = self
1689 return e
Fred Drake55c38192000-06-29 19:39:57 +00001690
1691 def createAttributeNS(self, namespaceURI, qualifiedName):
Fred Drake4ccf4a12000-11-21 22:02:22 +00001692 prefix, localName = _nssplit(qualifiedName)
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001693 a = Attr(qualifiedName, namespaceURI, localName, prefix)
1694 a.ownerDocument = self
Martin v. Löwiscb67ea12001-03-31 16:30:40 +00001695 a.value = ""
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001696 return a
Fred Drake55c38192000-06-29 19:39:57 +00001697
Martin v. Löwis787354c2003-01-25 15:28:29 +00001698 # A couple of implementation-specific helpers to create node types
1699 # not supported by the W3C DOM specs:
1700
1701 def _create_entity(self, name, publicId, systemId, notationName):
1702 e = Entity(name, publicId, systemId, notationName)
1703 e.ownerDocument = self
1704 return e
1705
1706 def _create_notation(self, name, publicId, systemId):
1707 n = Notation(name, publicId, systemId)
1708 n.ownerDocument = self
1709 return n
1710
1711 def getElementById(self, id):
Guido van Rossum1b01e5c2006-08-19 02:45:06 +00001712 if id in self._id_cache:
Martin v. Löwis787354c2003-01-25 15:28:29 +00001713 return self._id_cache[id]
1714 if not (self._elem_info or self._magic_id_count):
1715 return None
1716
1717 stack = self._id_search_stack
1718 if stack is None:
1719 # we never searched before, or the cache has been cleared
1720 stack = [self.documentElement]
1721 self._id_search_stack = stack
1722 elif not stack:
1723 # Previous search was completed and cache is still valid;
1724 # no matching node.
1725 return None
1726
1727 result = None
1728 while stack:
1729 node = stack.pop()
1730 # add child elements to stack for continued searching
1731 stack.extend([child for child in node.childNodes
1732 if child.nodeType in _nodeTypes_with_children])
1733 # check this node
1734 info = self._get_elem_info(node)
1735 if info:
1736 # We have to process all ID attributes before
1737 # returning in order to get all the attributes set to
1738 # be IDs using Element.setIdAttribute*().
1739 for attr in node.attributes.values():
1740 if attr.namespaceURI:
1741 if info.isIdNS(attr.namespaceURI, attr.localName):
1742 self._id_cache[attr.value] = node
1743 if attr.value == id:
1744 result = node
1745 elif not node._magic_id_nodes:
1746 break
1747 elif info.isId(attr.name):
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 attr._is_id:
1754 self._id_cache[attr.value] = node
1755 if attr.value == id:
1756 result = node
1757 elif node._magic_id_nodes == 1:
1758 break
1759 elif node._magic_id_nodes:
1760 for attr in node.attributes.values():
1761 if attr._is_id:
1762 self._id_cache[attr.value] = node
1763 if attr.value == id:
1764 result = node
1765 if result is not None:
1766 break
1767 return result
1768
Fred Drake1f549022000-09-24 05:21:58 +00001769 def getElementsByTagName(self, name):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001770 return _get_elements_by_tagName_helper(self, name, NodeList())
Fred Drakefbe7b4f2001-07-04 06:25:53 +00001771
1772 def getElementsByTagNameNS(self, namespaceURI, localName):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001773 return _get_elements_by_tagName_ns_helper(
1774 self, namespaceURI, localName, NodeList())
1775
1776 def isSupported(self, feature, version):
1777 return self.implementation.hasFeature(feature, version)
1778
1779 def importNode(self, node, deep):
1780 if node.nodeType == Node.DOCUMENT_NODE:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001781 raise xml.dom.NotSupportedErr("cannot import document nodes")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001782 elif node.nodeType == Node.DOCUMENT_TYPE_NODE:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001783 raise xml.dom.NotSupportedErr("cannot import document type nodes")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001784 return _clone_node(node, deep, self)
Fred Drake55c38192000-06-29 19:39:57 +00001785
Martin v. Löwis7d650ca2002-06-30 15:05:00 +00001786 def writexml(self, writer, indent="", addindent="", newl="",
1787 encoding = None):
1788 if encoding is None:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001789 writer.write('<?xml version="1.0" ?>'+newl)
Martin v. Löwis7d650ca2002-06-30 15:05:00 +00001790 else:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001791 writer.write('<?xml version="1.0" encoding="%s"?>%s' % (encoding, newl))
Fred Drake55c38192000-06-29 19:39:57 +00001792 for node in self.childNodes:
Martin v. Löwis46fa39a2001-02-06 00:14:08 +00001793 node.writexml(writer, indent, addindent, newl)
Fred Drake55c38192000-06-29 19:39:57 +00001794
Martin v. Löwis787354c2003-01-25 15:28:29 +00001795 # DOM Level 3 (WD 9 April 2002)
1796
1797 def renameNode(self, n, namespaceURI, name):
1798 if n.ownerDocument is not self:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001799 raise xml.dom.WrongDocumentErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001800 "cannot rename nodes from other documents;\n"
1801 "expected %s,\nfound %s" % (self, n.ownerDocument))
1802 if n.nodeType not in (Node.ELEMENT_NODE, Node.ATTRIBUTE_NODE):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001803 raise xml.dom.NotSupportedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001804 "renameNode() only applies to element and attribute nodes")
1805 if namespaceURI != EMPTY_NAMESPACE:
1806 if ':' in name:
1807 prefix, localName = name.split(':', 1)
1808 if ( prefix == "xmlns"
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001809 and namespaceURI != xml.dom.XMLNS_NAMESPACE):
1810 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001811 "illegal use of 'xmlns' prefix")
1812 else:
1813 if ( name == "xmlns"
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001814 and namespaceURI != xml.dom.XMLNS_NAMESPACE
Martin v. Löwis787354c2003-01-25 15:28:29 +00001815 and n.nodeType == Node.ATTRIBUTE_NODE):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001816 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001817 "illegal use of the 'xmlns' attribute")
1818 prefix = None
1819 localName = name
1820 else:
1821 prefix = None
1822 localName = None
1823 if n.nodeType == Node.ATTRIBUTE_NODE:
1824 element = n.ownerElement
1825 if element is not None:
1826 is_id = n._is_id
1827 element.removeAttributeNode(n)
1828 else:
1829 element = None
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001830 n.prefix = prefix
1831 n._localName = localName
1832 n.namespaceURI = namespaceURI
1833 n.nodeName = name
Martin v. Löwis787354c2003-01-25 15:28:29 +00001834 if n.nodeType == Node.ELEMENT_NODE:
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001835 n.tagName = name
Martin v. Löwis787354c2003-01-25 15:28:29 +00001836 else:
1837 # attribute node
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001838 n.name = name
Martin v. Löwis787354c2003-01-25 15:28:29 +00001839 if element is not None:
1840 element.setAttributeNode(n)
1841 if is_id:
1842 element.setIdAttributeNode(n)
1843 # It's not clear from a semantic perspective whether we should
1844 # call the user data handlers for the NODE_RENAMED event since
1845 # we're re-using the existing node. The draft spec has been
1846 # interpreted as meaning "no, don't call the handler unless a
1847 # new node is created."
1848 return n
1849
1850defproperty(Document, "documentElement",
1851 doc="Top-level element of this document.")
1852
1853
1854def _clone_node(node, deep, newOwnerDocument):
1855 """
1856 Clone a node and give it the new owner document.
1857 Called by Node.cloneNode and Document.importNode
1858 """
1859 if node.ownerDocument.isSameNode(newOwnerDocument):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001860 operation = xml.dom.UserDataHandler.NODE_CLONED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001861 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001862 operation = xml.dom.UserDataHandler.NODE_IMPORTED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001863 if node.nodeType == Node.ELEMENT_NODE:
1864 clone = newOwnerDocument.createElementNS(node.namespaceURI,
1865 node.nodeName)
1866 for attr in node.attributes.values():
1867 clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value)
1868 a = clone.getAttributeNodeNS(attr.namespaceURI, attr.localName)
1869 a.specified = attr.specified
1870
1871 if deep:
1872 for child in node.childNodes:
1873 c = _clone_node(child, deep, newOwnerDocument)
1874 clone.appendChild(c)
1875
1876 elif node.nodeType == Node.DOCUMENT_FRAGMENT_NODE:
1877 clone = newOwnerDocument.createDocumentFragment()
1878 if deep:
1879 for child in node.childNodes:
1880 c = _clone_node(child, deep, newOwnerDocument)
1881 clone.appendChild(c)
1882
1883 elif node.nodeType == Node.TEXT_NODE:
1884 clone = newOwnerDocument.createTextNode(node.data)
1885 elif node.nodeType == Node.CDATA_SECTION_NODE:
1886 clone = newOwnerDocument.createCDATASection(node.data)
1887 elif node.nodeType == Node.PROCESSING_INSTRUCTION_NODE:
1888 clone = newOwnerDocument.createProcessingInstruction(node.target,
1889 node.data)
1890 elif node.nodeType == Node.COMMENT_NODE:
1891 clone = newOwnerDocument.createComment(node.data)
1892 elif node.nodeType == Node.ATTRIBUTE_NODE:
1893 clone = newOwnerDocument.createAttributeNS(node.namespaceURI,
1894 node.nodeName)
1895 clone.specified = True
1896 clone.value = node.value
1897 elif node.nodeType == Node.DOCUMENT_TYPE_NODE:
1898 assert node.ownerDocument is not newOwnerDocument
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001899 operation = xml.dom.UserDataHandler.NODE_IMPORTED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001900 clone = newOwnerDocument.implementation.createDocumentType(
1901 node.name, node.publicId, node.systemId)
1902 clone.ownerDocument = newOwnerDocument
1903 if deep:
1904 clone.entities._seq = []
1905 clone.notations._seq = []
1906 for n in node.notations._seq:
1907 notation = Notation(n.nodeName, n.publicId, n.systemId)
1908 notation.ownerDocument = newOwnerDocument
1909 clone.notations._seq.append(notation)
1910 if hasattr(n, '_call_user_data_handler'):
1911 n._call_user_data_handler(operation, n, notation)
1912 for e in node.entities._seq:
1913 entity = Entity(e.nodeName, e.publicId, e.systemId,
1914 e.notationName)
1915 entity.actualEncoding = e.actualEncoding
1916 entity.encoding = e.encoding
1917 entity.version = e.version
1918 entity.ownerDocument = newOwnerDocument
1919 clone.entities._seq.append(entity)
1920 if hasattr(e, '_call_user_data_handler'):
1921 e._call_user_data_handler(operation, n, entity)
1922 else:
1923 # Note the cloning of Document and DocumentType nodes is
Ezio Melotti13925002011-03-16 11:05:33 +02001924 # implementation specific. minidom handles those cases
Martin v. Löwis787354c2003-01-25 15:28:29 +00001925 # directly in the cloneNode() methods.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001926 raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node))
Martin v. Löwis787354c2003-01-25 15:28:29 +00001927
1928 # Check for _call_user_data_handler() since this could conceivably
1929 # used with other DOM implementations (one of the FourThought
1930 # DOMs, perhaps?).
1931 if hasattr(node, '_call_user_data_handler'):
1932 node._call_user_data_handler(operation, node, clone)
1933 return clone
1934
1935
1936def _nssplit(qualifiedName):
1937 fields = qualifiedName.split(':', 1)
1938 if len(fields) == 2:
1939 return fields
1940 else:
1941 return (None, fields[0])
1942
1943
Martin v. Löwis787354c2003-01-25 15:28:29 +00001944def _do_pulldom_parse(func, args, kwargs):
Raymond Hettingerff41c482003-04-06 09:01:11 +00001945 events = func(*args, **kwargs)
Fred Drake1f549022000-09-24 05:21:58 +00001946 toktype, rootNode = events.getEvent()
1947 events.expandNode(rootNode)
Martin v. Löwisb417be22001-02-06 01:16:06 +00001948 events.clear()
Fred Drake55c38192000-06-29 19:39:57 +00001949 return rootNode
1950
Martin v. Löwis787354c2003-01-25 15:28:29 +00001951def parse(file, parser=None, bufsize=None):
Fred Drakef7cf40d2000-12-14 18:16:11 +00001952 """Parse a file into a DOM by filename or file object."""
Martin v. Löwis787354c2003-01-25 15:28:29 +00001953 if parser is None and not bufsize:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001954 from xml.dom import expatbuilder
Martin v. Löwis787354c2003-01-25 15:28:29 +00001955 return expatbuilder.parse(file)
1956 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001957 from xml.dom import pulldom
Raymond Hettingerff41c482003-04-06 09:01:11 +00001958 return _do_pulldom_parse(pulldom.parse, (file,),
Martin v. Löwis787354c2003-01-25 15:28:29 +00001959 {'parser': parser, 'bufsize': bufsize})
Fred Drake55c38192000-06-29 19:39:57 +00001960
Martin v. Löwis787354c2003-01-25 15:28:29 +00001961def parseString(string, parser=None):
Fred Drakef7cf40d2000-12-14 18:16:11 +00001962 """Parse a file into a DOM from a string."""
Martin v. Löwis787354c2003-01-25 15:28:29 +00001963 if parser is None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001964 from xml.dom import expatbuilder
Martin v. Löwis787354c2003-01-25 15:28:29 +00001965 return expatbuilder.parseString(string)
1966 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001967 from xml.dom import pulldom
Martin v. Löwis787354c2003-01-25 15:28:29 +00001968 return _do_pulldom_parse(pulldom.parseString, (string,),
1969 {'parser': parser})
Martin v. Löwis7edbd4f2001-02-22 14:05:50 +00001970
Martin v. Löwis787354c2003-01-25 15:28:29 +00001971def getDOMImplementation(features=None):
1972 if features:
Christian Heimesc9543e42007-11-28 08:28:28 +00001973 if isinstance(features, str):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001974 features = domreg._parse_feature_string(features)
1975 for f, v in features:
1976 if not Document.implementation.hasFeature(f, v):
1977 return None
Martin v. Löwis7edbd4f2001-02-22 14:05:50 +00001978 return Document.implementation