blob: 55c4ce11c2f067979727496c80a6bfe92a0b79d0 [file] [log] [blame]
Ezio Melottida4b5b82013-01-22 22:47:57 +02001"""Simple implementation of the Level 1 DOM.
2
3Namespaces and other minor Level 2 features are also supported.
Fred Drake55c38192000-06-29 19:39:57 +00004
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +00005parse("foo.xml")
Paul Prescod623511b2000-07-21 22:05:49 +00006
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +00007parseString("<foo><bar/></foo>")
Paul Prescod623511b2000-07-21 22:05:49 +00008
Fred Drake55c38192000-06-29 19:39:57 +00009Todo:
10=====
11 * convenience methods for getting elements and text.
12 * more testing
13 * bring some of the writer and linearizer code into conformance with this
14 interface
15 * SAX 2 namespaces
16"""
17
Guido van Rossum3e1f85e2007-07-27 18:03:11 +000018import io
Thomas Wouters0e3f5912006-08-11 14:57:12 +000019import xml.dom
Fred Drake55c38192000-06-29 19:39:57 +000020
Thomas Wouters0e3f5912006-08-11 14:57:12 +000021from xml.dom import EMPTY_NAMESPACE, EMPTY_PREFIX, XMLNS_NAMESPACE, domreg
22from xml.dom.minicompat import *
23from xml.dom.xmlbuilder import DOMImplementationLS, DocumentLS
Fred Drake3ac6a092001-09-28 04:33:06 +000024
Martin v. Löwis787354c2003-01-25 15:28:29 +000025# This is used by the ID-cache invalidation checks; the list isn't
26# actually complete, since the nodes being checked will never be the
27# DOCUMENT_NODE or DOCUMENT_FRAGMENT_NODE. (The node being checked is
28# the node being added or removed, not the node being modified.)
29#
Thomas Wouters0e3f5912006-08-11 14:57:12 +000030_nodeTypes_with_children = (xml.dom.Node.ELEMENT_NODE,
31 xml.dom.Node.ENTITY_REFERENCE_NODE)
Martin v. Löwis95700f72002-03-15 13:51:59 +000032
Fred Drake3ac6a092001-09-28 04:33:06 +000033
Thomas Wouters0e3f5912006-08-11 14:57:12 +000034class Node(xml.dom.Node):
Martin v. Löwis126f2f62001-03-13 10:50:13 +000035 namespaceURI = None # this is non-null only for elements and attributes
Fred Drake575712e2001-09-28 20:25:45 +000036 parentNode = None
37 ownerDocument = None
Martin v. Löwis787354c2003-01-25 15:28:29 +000038 nextSibling = None
39 previousSibling = None
Martin v. Löwis52ce0d02001-01-27 08:47:37 +000040
Martin v. Löwis787354c2003-01-25 15:28:29 +000041 prefix = EMPTY_PREFIX # non-null only for NS elements and attributes
Fred Drake55c38192000-06-29 19:39:57 +000042
Jack Diederich4dafcc42006-11-28 19:15:13 +000043 def __bool__(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +000044 return True
Fred Drake55c38192000-06-29 19:39:57 +000045
Georg Brandlfe991052009-09-16 15:54:04 +000046 def toxml(self, encoding=None):
Martin v. Löwis7d650ca2002-06-30 15:05:00 +000047 return self.toprettyxml("", "", encoding)
Fred Drake55c38192000-06-29 19:39:57 +000048
Guido van Rossum3e1f85e2007-07-27 18:03:11 +000049 def toprettyxml(self, indent="\t", newl="\n", encoding=None):
Eli Bendersky8a805022012-07-13 09:52:39 +030050 if encoding is None:
51 writer = io.StringIO()
52 else:
53 writer = io.TextIOWrapper(io.BytesIO(),
54 encoding=encoding,
55 errors="xmlcharrefreplace",
56 newline='\n')
Martin v. Löwis7d650ca2002-06-30 15:05:00 +000057 if self.nodeType == Node.DOCUMENT_NODE:
58 # Can pass encoding only to document, to put it into XML header
59 self.writexml(writer, "", indent, newl, encoding)
60 else:
61 self.writexml(writer, "", indent, newl)
Guido van Rossum3e1f85e2007-07-27 18:03:11 +000062 if encoding is None:
Eli Bendersky8a805022012-07-13 09:52:39 +030063 return writer.getvalue()
Guido van Rossum3e1f85e2007-07-27 18:03:11 +000064 else:
Eli Bendersky8a805022012-07-13 09:52:39 +030065 return writer.detach().getvalue()
Martin v. Löwis46fa39a2001-02-06 00:14:08 +000066
Fred Drake1f549022000-09-24 05:21:58 +000067 def hasChildNodes(self):
Florent Xicluna8cf4b512012-03-05 12:37:02 +010068 return bool(self.childNodes)
Martin v. Löwis787354c2003-01-25 15:28:29 +000069
70 def _get_childNodes(self):
71 return self.childNodes
Fred Drake55c38192000-06-29 19:39:57 +000072
Fred Drake1f549022000-09-24 05:21:58 +000073 def _get_firstChild(self):
Fred Drake4ccf4a12000-11-21 22:02:22 +000074 if self.childNodes:
75 return self.childNodes[0]
Paul Prescod73678da2000-07-01 04:58:47 +000076
Fred Drake1f549022000-09-24 05:21:58 +000077 def _get_lastChild(self):
Fred Drake4ccf4a12000-11-21 22:02:22 +000078 if self.childNodes:
79 return self.childNodes[-1]
Paul Prescod73678da2000-07-01 04:58:47 +000080
Fred Drake1f549022000-09-24 05:21:58 +000081 def insertBefore(self, newChild, refChild):
Martin v. Löwis126f2f62001-03-13 10:50:13 +000082 if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE:
Fred Drakee50959a2001-12-06 04:32:18 +000083 for c in tuple(newChild.childNodes):
Martin v. Löwis126f2f62001-03-13 10:50:13 +000084 self.insertBefore(c, refChild)
85 ### The DOM does not clearly specify what to return in this case
86 return newChild
Martin v. Löwis787354c2003-01-25 15:28:29 +000087 if newChild.nodeType not in self._child_node_types:
Thomas Wouters0e3f5912006-08-11 14:57:12 +000088 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +000089 "%s cannot be child of %s" % (repr(newChild), repr(self)))
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +000090 if newChild.parentNode is not None:
91 newChild.parentNode.removeChild(newChild)
Fred Drake4ccf4a12000-11-21 22:02:22 +000092 if refChild is None:
93 self.appendChild(newChild)
94 else:
Martin v. Löwis787354c2003-01-25 15:28:29 +000095 try:
96 index = self.childNodes.index(refChild)
97 except ValueError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +000098 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +000099 if newChild.nodeType in _nodeTypes_with_children:
100 _clear_id_cache(self)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000101 self.childNodes.insert(index, newChild)
102 newChild.nextSibling = refChild
103 refChild.previousSibling = newChild
104 if index:
105 node = self.childNodes[index-1]
106 node.nextSibling = newChild
107 newChild.previousSibling = node
108 else:
109 newChild.previousSibling = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000110 newChild.parentNode = self
Fred Drake4ccf4a12000-11-21 22:02:22 +0000111 return newChild
Fred Drake55c38192000-06-29 19:39:57 +0000112
Fred Drake1f549022000-09-24 05:21:58 +0000113 def appendChild(self, node):
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000114 if node.nodeType == self.DOCUMENT_FRAGMENT_NODE:
Fred Drakee50959a2001-12-06 04:32:18 +0000115 for c in tuple(node.childNodes):
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000116 self.appendChild(c)
117 ### The DOM does not clearly specify what to return in this case
118 return node
Martin v. Löwis787354c2003-01-25 15:28:29 +0000119 if node.nodeType not in self._child_node_types:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000120 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000121 "%s cannot be child of %s" % (repr(node), repr(self)))
122 elif node.nodeType in _nodeTypes_with_children:
123 _clear_id_cache(self)
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +0000124 if node.parentNode is not None:
125 node.parentNode.removeChild(node)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000126 _append_child(self, node)
Fred Drake13a30692000-10-09 20:04:16 +0000127 node.nextSibling = None
Paul Prescod73678da2000-07-01 04:58:47 +0000128 return node
129
Fred Drake1f549022000-09-24 05:21:58 +0000130 def replaceChild(self, newChild, oldChild):
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000131 if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE:
132 refChild = oldChild.nextSibling
133 self.removeChild(oldChild)
134 return self.insertBefore(newChild, refChild)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000135 if newChild.nodeType not in self._child_node_types:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000136 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000137 "%s cannot be child of %s" % (repr(newChild), repr(self)))
Fred Drake4ccf4a12000-11-21 22:02:22 +0000138 if newChild is oldChild:
139 return
Andrew M. Kuchling841d25e2005-11-22 19:03:16 +0000140 if newChild.parentNode is not None:
141 newChild.parentNode.removeChild(newChild)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000142 try:
143 index = self.childNodes.index(oldChild)
144 except ValueError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000145 raise xml.dom.NotFoundErr()
Fred Drake4ccf4a12000-11-21 22:02:22 +0000146 self.childNodes[index] = newChild
Martin v. Löwis787354c2003-01-25 15:28:29 +0000147 newChild.parentNode = self
148 oldChild.parentNode = None
149 if (newChild.nodeType in _nodeTypes_with_children
150 or oldChild.nodeType in _nodeTypes_with_children):
151 _clear_id_cache(self)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000152 newChild.nextSibling = oldChild.nextSibling
153 newChild.previousSibling = oldChild.previousSibling
Martin v. Löwis156c3372000-12-28 18:40:56 +0000154 oldChild.nextSibling = None
Fred Drake4ccf4a12000-11-21 22:02:22 +0000155 oldChild.previousSibling = None
Martin v. Löwis156c3372000-12-28 18:40:56 +0000156 if newChild.previousSibling:
157 newChild.previousSibling.nextSibling = newChild
158 if newChild.nextSibling:
159 newChild.nextSibling.previousSibling = newChild
Fred Drake4ccf4a12000-11-21 22:02:22 +0000160 return oldChild
Paul Prescod73678da2000-07-01 04:58:47 +0000161
Fred Drake1f549022000-09-24 05:21:58 +0000162 def removeChild(self, oldChild):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000163 try:
164 self.childNodes.remove(oldChild)
165 except ValueError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000166 raise xml.dom.NotFoundErr()
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +0000167 if oldChild.nextSibling is not None:
168 oldChild.nextSibling.previousSibling = oldChild.previousSibling
169 if oldChild.previousSibling is not None:
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000170 oldChild.previousSibling.nextSibling = oldChild.nextSibling
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +0000171 oldChild.nextSibling = oldChild.previousSibling = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000172 if oldChild.nodeType in _nodeTypes_with_children:
173 _clear_id_cache(self)
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000174
Martin v. Löwis787354c2003-01-25 15:28:29 +0000175 oldChild.parentNode = None
Fred Drake4ccf4a12000-11-21 22:02:22 +0000176 return oldChild
177
178 def normalize(self):
Fred Drakef7cf40d2000-12-14 18:16:11 +0000179 L = []
180 for child in self.childNodes:
181 if child.nodeType == Node.TEXT_NODE:
R. David Murraydc6da8a2009-04-09 22:16:43 +0000182 if not child.data:
183 # empty text node; discard
184 if L:
185 L[-1].nextSibling = child.nextSibling
186 if child.nextSibling:
187 child.nextSibling.previousSibling = child.previousSibling
188 child.unlink()
189 elif L and L[-1].nodeType == child.nodeType:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000190 # collapse text node
191 node = L[-1]
Martin v. Löwis787354c2003-01-25 15:28:29 +0000192 node.data = node.data + child.data
Fred Drake4ccf4a12000-11-21 22:02:22 +0000193 node.nextSibling = child.nextSibling
R. David Murraydc6da8a2009-04-09 22:16:43 +0000194 if child.nextSibling:
195 child.nextSibling.previousSibling = node
Fred Drake4ccf4a12000-11-21 22:02:22 +0000196 child.unlink()
R. David Murraydc6da8a2009-04-09 22:16:43 +0000197 else:
Fred Drakef7cf40d2000-12-14 18:16:11 +0000198 L.append(child)
Fred Drakef7cf40d2000-12-14 18:16:11 +0000199 else:
Fred Drakef7cf40d2000-12-14 18:16:11 +0000200 L.append(child)
201 if child.nodeType == Node.ELEMENT_NODE:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000202 child.normalize()
Fred Drakef7cf40d2000-12-14 18:16:11 +0000203 self.childNodes[:] = L
Paul Prescod73678da2000-07-01 04:58:47 +0000204
Fred Drake1f549022000-09-24 05:21:58 +0000205 def cloneNode(self, deep):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000206 return _clone_node(self, deep, self.ownerDocument or self)
Fred Drake55c38192000-06-29 19:39:57 +0000207
Martin v. Löwis787354c2003-01-25 15:28:29 +0000208 def isSupported(self, feature, version):
209 return self.ownerDocument.implementation.hasFeature(feature, version)
210
211 def _get_localName(self):
212 # Overridden in Element and Attr where localName can be Non-Null
213 return None
214
215 # Node interfaces from Level 3 (WD 9 April 2002)
Fred Drake25239772001-02-02 19:40:19 +0000216
217 def isSameNode(self, other):
218 return self is other
219
Martin v. Löwis787354c2003-01-25 15:28:29 +0000220 def getInterface(self, feature):
221 if self.isSupported(feature, None):
222 return self
223 else:
224 return None
225
226 # The "user data" functions use a dictionary that is only present
227 # if some user data has been set, so be careful not to assume it
228 # exists.
229
230 def getUserData(self, key):
231 try:
232 return self._user_data[key][0]
233 except (AttributeError, KeyError):
234 return None
235
236 def setUserData(self, key, data, handler):
237 old = None
238 try:
239 d = self._user_data
240 except AttributeError:
241 d = {}
242 self._user_data = d
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000243 if key in d:
Martin v. Löwis787354c2003-01-25 15:28:29 +0000244 old = d[key][0]
245 if data is None:
246 # ignore handlers passed for None
247 handler = None
248 if old is not None:
249 del d[key]
250 else:
251 d[key] = (data, handler)
252 return old
253
254 def _call_user_data_handler(self, operation, src, dst):
255 if hasattr(self, "_user_data"):
Brett Cannon861fd6f2007-02-21 22:05:37 +0000256 for key, (data, handler) in list(self._user_data.items()):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000257 if handler is not None:
258 handler.handle(operation, key, data, src, dst)
259
Fred Drake25239772001-02-02 19:40:19 +0000260 # minidom-specific API:
261
Fred Drake1f549022000-09-24 05:21:58 +0000262 def unlink(self):
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000263 self.parentNode = self.ownerDocument = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000264 if self.childNodes:
265 for child in self.childNodes:
266 child.unlink()
267 self.childNodes = NodeList()
Paul Prescod4221ff02000-10-13 20:11:42 +0000268 self.previousSibling = None
269 self.nextSibling = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000270
Kristján Valur Jónsson17173cf2010-06-09 08:13:42 +0000271 # A Node is its own context manager, to ensure that an unlink() call occurs.
272 # This is similar to how a file object works.
273 def __enter__(self):
274 return self
275
276 def __exit__(self, et, ev, tb):
277 self.unlink()
278
Martin v. Löwis787354c2003-01-25 15:28:29 +0000279defproperty(Node, "firstChild", doc="First child node, or None.")
280defproperty(Node, "lastChild", doc="Last child node, or None.")
281defproperty(Node, "localName", doc="Namespace-local name of this node.")
282
283
284def _append_child(self, node):
285 # fast path with less checks; usable by DOM builders if careful
286 childNodes = self.childNodes
287 if childNodes:
288 last = childNodes[-1]
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100289 node.previousSibling = last
290 last.nextSibling = node
Martin v. Löwis787354c2003-01-25 15:28:29 +0000291 childNodes.append(node)
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100292 node.parentNode = self
Martin v. Löwis787354c2003-01-25 15:28:29 +0000293
294def _in_document(node):
295 # return True iff node is part of a document tree
296 while node is not None:
297 if node.nodeType == Node.DOCUMENT_NODE:
298 return True
299 node = node.parentNode
300 return False
Fred Drake55c38192000-06-29 19:39:57 +0000301
Fred Drake1f549022000-09-24 05:21:58 +0000302def _write_data(writer, data):
Fred Drake55c38192000-06-29 19:39:57 +0000303 "Writes datachars to writer."
Georg Brandlb9cd72a2010-10-15 17:58:45 +0000304 if data:
305 data = data.replace("&", "&amp;").replace("<", "&lt;"). \
306 replace("\"", "&quot;").replace(">", "&gt;")
307 writer.write(data)
Fred Drake55c38192000-06-29 19:39:57 +0000308
Martin v. Löwis787354c2003-01-25 15:28:29 +0000309def _get_elements_by_tagName_helper(parent, name, rc):
Fred Drake55c38192000-06-29 19:39:57 +0000310 for node in parent.childNodes:
Fred Drake1f549022000-09-24 05:21:58 +0000311 if node.nodeType == Node.ELEMENT_NODE and \
312 (name == "*" or node.tagName == name):
313 rc.append(node)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000314 _get_elements_by_tagName_helper(node, name, rc)
Fred Drake55c38192000-06-29 19:39:57 +0000315 return rc
316
Martin v. Löwis787354c2003-01-25 15:28:29 +0000317def _get_elements_by_tagName_ns_helper(parent, nsURI, localName, rc):
Fred Drake55c38192000-06-29 19:39:57 +0000318 for node in parent.childNodes:
Fred Drake1f549022000-09-24 05:21:58 +0000319 if node.nodeType == Node.ELEMENT_NODE:
Martin v. Löwised525fb2001-06-03 14:06:42 +0000320 if ((localName == "*" or node.localName == localName) and
Fred Drake1f549022000-09-24 05:21:58 +0000321 (nsURI == "*" or node.namespaceURI == nsURI)):
322 rc.append(node)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000323 _get_elements_by_tagName_ns_helper(node, nsURI, localName, rc)
Fred Drakef7cf40d2000-12-14 18:16:11 +0000324 return rc
Fred Drake55c38192000-06-29 19:39:57 +0000325
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000326class DocumentFragment(Node):
327 nodeType = Node.DOCUMENT_FRAGMENT_NODE
328 nodeName = "#document-fragment"
329 nodeValue = None
330 attributes = None
331 parentNode = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000332 _child_node_types = (Node.ELEMENT_NODE,
333 Node.TEXT_NODE,
334 Node.CDATA_SECTION_NODE,
335 Node.ENTITY_REFERENCE_NODE,
336 Node.PROCESSING_INSTRUCTION_NODE,
337 Node.COMMENT_NODE,
338 Node.NOTATION_NODE)
339
340 def __init__(self):
341 self.childNodes = NodeList()
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000342
343
Fred Drake55c38192000-06-29 19:39:57 +0000344class Attr(Node):
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100345 __slots__=('_name', '_value', 'namespaceURI',
346 '_prefix', 'childNodes', '_localName', 'ownerDocument', 'ownerElement')
Fred Drake1f549022000-09-24 05:21:58 +0000347 nodeType = Node.ATTRIBUTE_NODE
Fred Drake4ccf4a12000-11-21 22:02:22 +0000348 attributes = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000349 specified = False
350 _is_id = False
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000351
Martin v. Löwis787354c2003-01-25 15:28:29 +0000352 _child_node_types = (Node.TEXT_NODE, Node.ENTITY_REFERENCE_NODE)
353
354 def __init__(self, qName, namespaceURI=EMPTY_NAMESPACE, localName=None,
355 prefix=None):
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100356 self.ownerElement = None
357 self._name = qName
358 self.namespaceURI = namespaceURI
359 self._prefix = prefix
360 self.childNodes = NodeList()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000361
362 # Add the single child node that represents the value of the attr
363 self.childNodes.append(Text())
364
Paul Prescod73678da2000-07-01 04:58:47 +0000365 # nodeValue and value are set elsewhere
Fred Drake55c38192000-06-29 19:39:57 +0000366
Martin v. Löwis787354c2003-01-25 15:28:29 +0000367 def _get_localName(self):
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100368 try:
369 return self._localName
370 except AttributeError:
371 return self.nodeName.split(":", 1)[-1]
Martin v. Löwis787354c2003-01-25 15:28:29 +0000372
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):
Martin v. Löwis67245a62012-03-05 07:01:49 +0100726 if self._attrs is None:
727 return ""
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000728 try:
729 return self._attrs[attname].value
730 except KeyError:
731 return ""
Fred Drake55c38192000-06-29 19:39:57 +0000732
Fred Drake1f549022000-09-24 05:21:58 +0000733 def getAttributeNS(self, namespaceURI, localName):
Martin v. Löwis67245a62012-03-05 07:01:49 +0100734 if self._attrsNS is None:
735 return ""
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000736 try:
737 return self._attrsNS[(namespaceURI, localName)].value
738 except KeyError:
739 return ""
Fred Drake1f549022000-09-24 05:21:58 +0000740
741 def setAttribute(self, attname, value):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000742 attr = self.getAttributeNode(attname)
743 if attr is None:
744 attr = Attr(attname)
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100745 attr.value = value # also sets nodeValue
746 attr.ownerDocument = self.ownerDocument
Martin v. Löwis787354c2003-01-25 15:28:29 +0000747 self.setAttributeNode(attr)
748 elif value != attr.value:
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100749 attr.value = value
Martin v. Löwis787354c2003-01-25 15:28:29 +0000750 if attr.isId:
751 _clear_id_cache(self)
Fred Drake55c38192000-06-29 19:39:57 +0000752
Fred Drake1f549022000-09-24 05:21:58 +0000753 def setAttributeNS(self, namespaceURI, qualifiedName, value):
754 prefix, localname = _nssplit(qualifiedName)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000755 attr = self.getAttributeNodeNS(namespaceURI, localname)
756 if attr is None:
Martin v. Löwis787354c2003-01-25 15:28:29 +0000757 attr = Attr(qualifiedName, namespaceURI, localname, prefix)
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100758 attr.value = value
759 attr.ownerDocument = self.ownerDocument
Martin v. Löwis787354c2003-01-25 15:28:29 +0000760 self.setAttributeNode(attr)
761 else:
Martin v. Löwis787354c2003-01-25 15:28:29 +0000762 if value != attr.value:
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100763 attr.value = value
Martin v. Löwis787354c2003-01-25 15:28:29 +0000764 if attr.isId:
765 _clear_id_cache(self)
766 if attr.prefix != prefix:
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100767 attr.prefix = prefix
768 attr.nodeName = qualifiedName
Fred Drake55c38192000-06-29 19:39:57 +0000769
Fred Drake1f549022000-09-24 05:21:58 +0000770 def getAttributeNode(self, attrname):
Martin v. Löwis7b771882012-02-19 20:55:05 +0100771 if self._attrs is None:
772 return None
Fred Drake1f549022000-09-24 05:21:58 +0000773 return self._attrs.get(attrname)
Paul Prescod73678da2000-07-01 04:58:47 +0000774
Fred Drake1f549022000-09-24 05:21:58 +0000775 def getAttributeNodeNS(self, namespaceURI, localName):
Martin v. Löwis7b771882012-02-19 20:55:05 +0100776 if self._attrsNS is None:
777 return None
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000778 return self._attrsNS.get((namespaceURI, localName))
Paul Prescod73678da2000-07-01 04:58:47 +0000779
Fred Drake1f549022000-09-24 05:21:58 +0000780 def setAttributeNode(self, attr):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000781 if attr.ownerElement not in (None, self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000782 raise xml.dom.InuseAttributeErr("attribute node already owned")
Martin v. Löwis7b771882012-02-19 20:55:05 +0100783 self._ensure_attributes()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000784 old1 = self._attrs.get(attr.name, None)
785 if old1 is not None:
786 self.removeAttributeNode(old1)
787 old2 = self._attrsNS.get((attr.namespaceURI, attr.localName), None)
788 if old2 is not None and old2 is not old1:
789 self.removeAttributeNode(old2)
790 _set_attribute_node(self, attr)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000791
Martin v. Löwis787354c2003-01-25 15:28:29 +0000792 if old1 is not attr:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000793 # It might have already been part of this node, in which case
794 # it doesn't represent a change, and should not be returned.
Martin v. Löwis787354c2003-01-25 15:28:29 +0000795 return old1
796 if old2 is not attr:
797 return old2
Fred Drake55c38192000-06-29 19:39:57 +0000798
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000799 setAttributeNodeNS = setAttributeNode
800
Fred Drake1f549022000-09-24 05:21:58 +0000801 def removeAttribute(self, name):
Martin v. Löwis7b771882012-02-19 20:55:05 +0100802 if self._attrsNS is None:
803 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000804 try:
805 attr = self._attrs[name]
806 except KeyError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000807 raise xml.dom.NotFoundErr()
Fred Drake1f549022000-09-24 05:21:58 +0000808 self.removeAttributeNode(attr)
Fred Drake55c38192000-06-29 19:39:57 +0000809
Fred Drake1f549022000-09-24 05:21:58 +0000810 def removeAttributeNS(self, namespaceURI, localName):
Martin v. Löwis7b771882012-02-19 20:55:05 +0100811 if self._attrsNS is None:
812 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000813 try:
814 attr = self._attrsNS[(namespaceURI, localName)]
815 except KeyError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000816 raise xml.dom.NotFoundErr()
Fred Drake1f549022000-09-24 05:21:58 +0000817 self.removeAttributeNode(attr)
Fred Drake55c38192000-06-29 19:39:57 +0000818
Fred Drake1f549022000-09-24 05:21:58 +0000819 def removeAttributeNode(self, node):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000820 if node is None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000821 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000822 try:
823 self._attrs[node.name]
824 except KeyError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000825 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000826 _clear_id_cache(self)
Paul Prescod73678da2000-07-01 04:58:47 +0000827 node.unlink()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000828 # Restore this since the node is still useful and otherwise
829 # unlinked
830 node.ownerDocument = self.ownerDocument
Fred Drake16f63292000-10-23 18:09:50 +0000831
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000832 removeAttributeNodeNS = removeAttributeNode
833
Martin v. Löwis156c3372000-12-28 18:40:56 +0000834 def hasAttribute(self, name):
Martin v. Löwis7b771882012-02-19 20:55:05 +0100835 if self._attrs is None:
836 return False
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000837 return name in self._attrs
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000838
Martin v. Löwis156c3372000-12-28 18:40:56 +0000839 def hasAttributeNS(self, namespaceURI, localName):
Martin v. Löwis7b771882012-02-19 20:55:05 +0100840 if self._attrsNS is None:
841 return False
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000842 return (namespaceURI, localName) in self._attrsNS
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000843
Fred Drake1f549022000-09-24 05:21:58 +0000844 def getElementsByTagName(self, name):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000845 return _get_elements_by_tagName_helper(self, name, NodeList())
Fred Drake55c38192000-06-29 19:39:57 +0000846
Fred Drake1f549022000-09-24 05:21:58 +0000847 def getElementsByTagNameNS(self, namespaceURI, localName):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000848 return _get_elements_by_tagName_ns_helper(
849 self, namespaceURI, localName, NodeList())
Fred Drake55c38192000-06-29 19:39:57 +0000850
Fred Drake1f549022000-09-24 05:21:58 +0000851 def __repr__(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000852 return "<DOM Element: %s at %#x>" % (self.tagName, id(self))
Fred Drake55c38192000-06-29 19:39:57 +0000853
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000854 def writexml(self, writer, indent="", addindent="", newl=""):
855 # indent = current indentation
856 # addindent = indentation to add to higher levels
857 # newl = newline string
858 writer.write(indent+"<" + self.tagName)
Fred Drake16f63292000-10-23 18:09:50 +0000859
Fred Drake4ccf4a12000-11-21 22:02:22 +0000860 attrs = self._get_attributes()
Brett Cannon861fd6f2007-02-21 22:05:37 +0000861 a_names = sorted(attrs.keys())
Fred Drake55c38192000-06-29 19:39:57 +0000862
863 for a_name in a_names:
Fred Drake1f549022000-09-24 05:21:58 +0000864 writer.write(" %s=\"" % a_name)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000865 _write_data(writer, attrs[a_name].value)
Fred Drake55c38192000-06-29 19:39:57 +0000866 writer.write("\"")
867 if self.childNodes:
R David Murray791744b2011-10-01 16:19:51 -0400868 writer.write(">")
Ezio Melotti8008f2a2011-11-18 17:34:26 +0200869 if (len(self.childNodes) == 1 and
870 self.childNodes[0].nodeType == Node.TEXT_NODE):
871 self.childNodes[0].writexml(writer, '', '', '')
872 else:
R David Murray791744b2011-10-01 16:19:51 -0400873 writer.write(newl)
Ezio Melotti8008f2a2011-11-18 17:34:26 +0200874 for node in self.childNodes:
875 node.writexml(writer, indent+addindent, addindent, newl)
876 writer.write(indent)
877 writer.write("</%s>%s" % (self.tagName, newl))
Fred Drake55c38192000-06-29 19:39:57 +0000878 else:
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000879 writer.write("/>%s"%(newl))
Fred Drake55c38192000-06-29 19:39:57 +0000880
Fred Drake1f549022000-09-24 05:21:58 +0000881 def _get_attributes(self):
Martin v. Löwis7b771882012-02-19 20:55:05 +0100882 self._ensure_attributes()
Fred Drake2998a552001-12-06 18:27:48 +0000883 return NamedNodeMap(self._attrs, self._attrsNS, self)
Fred Drake55c38192000-06-29 19:39:57 +0000884
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000885 def hasAttributes(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000886 if self._attrs:
887 return True
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000888 else:
Martin v. Löwis787354c2003-01-25 15:28:29 +0000889 return False
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000890
Martin v. Löwis787354c2003-01-25 15:28:29 +0000891 # DOM Level 3 attributes, based on the 22 Oct 2002 draft
892
893 def setIdAttribute(self, name):
894 idAttr = self.getAttributeNode(name)
895 self.setIdAttributeNode(idAttr)
896
897 def setIdAttributeNS(self, namespaceURI, localName):
898 idAttr = self.getAttributeNodeNS(namespaceURI, localName)
899 self.setIdAttributeNode(idAttr)
900
901 def setIdAttributeNode(self, idAttr):
902 if idAttr is None or not self.isSameNode(idAttr.ownerElement):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000903 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000904 if _get_containing_entref(self) is not None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000905 raise xml.dom.NoModificationAllowedErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000906 if not idAttr._is_id:
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100907 idAttr._is_id = True
Martin v. Löwis787354c2003-01-25 15:28:29 +0000908 self._magic_id_nodes += 1
909 self.ownerDocument._magic_id_count += 1
910 _clear_id_cache(self)
911
912defproperty(Element, "attributes",
913 doc="NamedNodeMap of attributes on the element.")
914defproperty(Element, "localName",
915 doc="Namespace-local name of this element.")
916
917
918def _set_attribute_node(element, attr):
919 _clear_id_cache(element)
Martin v. Löwis7b771882012-02-19 20:55:05 +0100920 element._ensure_attributes()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000921 element._attrs[attr.name] = attr
922 element._attrsNS[(attr.namespaceURI, attr.localName)] = attr
923
924 # This creates a circular reference, but Element.unlink()
925 # breaks the cycle since the references to the attribute
926 # dictionaries are tossed.
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100927 attr.ownerElement = element
Martin v. Löwis787354c2003-01-25 15:28:29 +0000928
929class Childless:
930 """Mixin that makes childless-ness easy to implement and avoids
931 the complexity of the Node methods that deal with children.
932 """
Florent Xicluna8cf4b512012-03-05 12:37:02 +0100933 __slots__ = ()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000934
Fred Drake4ccf4a12000-11-21 22:02:22 +0000935 attributes = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000936 childNodes = EmptyNodeList()
937 firstChild = None
938 lastChild = None
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000939
Martin v. Löwis787354c2003-01-25 15:28:29 +0000940 def _get_firstChild(self):
941 return None
Fred Drake55c38192000-06-29 19:39:57 +0000942
Martin v. Löwis787354c2003-01-25 15:28:29 +0000943 def _get_lastChild(self):
944 return None
Fred Drake1f549022000-09-24 05:21:58 +0000945
Martin v. Löwis787354c2003-01-25 15:28:29 +0000946 def appendChild(self, node):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000947 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000948 self.nodeName + " nodes cannot have children")
949
950 def hasChildNodes(self):
951 return False
952
953 def insertBefore(self, newChild, refChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000954 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000955 self.nodeName + " nodes do not have children")
956
957 def removeChild(self, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000958 raise xml.dom.NotFoundErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000959 self.nodeName + " nodes do not have children")
960
Andrew M. Kuchling688b9e32010-07-25 23:38:47 +0000961 def normalize(self):
962 # For childless nodes, normalize() has nothing to do.
963 pass
964
Martin v. Löwis787354c2003-01-25 15:28:29 +0000965 def replaceChild(self, newChild, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000966 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000967 self.nodeName + " nodes do not have children")
968
969
970class ProcessingInstruction(Childless, Node):
Fred Drake1f549022000-09-24 05:21:58 +0000971 nodeType = Node.PROCESSING_INSTRUCTION_NODE
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100972 __slots__ = ('target', 'data')
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000973
Fred Drake1f549022000-09-24 05:21:58 +0000974 def __init__(self, target, data):
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100975 self.target = target
976 self.data = data
Fred Drake55c38192000-06-29 19:39:57 +0000977
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100978 # nodeValue is an alias for data
979 def _get_nodeValue(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000980 return self.data
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100981 def _set_nodeValue(self, value):
982 self.data = data
983 nodeValue = property(_get_nodeValue, _set_nodeValue)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000984
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100985 # nodeName is an alias for target
986 def _get_nodeName(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000987 return self.target
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100988 def _set_nodeName(self, value):
989 self.target = value
990 nodeName = property(_get_nodeName, _set_nodeName)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000991
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000992 def writexml(self, writer, indent="", addindent="", newl=""):
993 writer.write("%s<?%s %s?>%s" % (indent,self.target, self.data, newl))
Fred Drake55c38192000-06-29 19:39:57 +0000994
Martin v. Löwis787354c2003-01-25 15:28:29 +0000995
996class CharacterData(Childless, Node):
Martin v. Löwis14aa2802012-02-19 20:25:12 +0100997 __slots__=('_data', 'ownerDocument','parentNode', 'previousSibling', 'nextSibling')
998
999 def __init__(self):
1000 self.ownerDocument = self.parentNode = None
1001 self.previousSibling = self.nextSibling = None
1002 self._data = ''
1003 Node.__init__(self)
1004
Martin v. Löwis787354c2003-01-25 15:28:29 +00001005 def _get_length(self):
1006 return len(self.data)
1007 __len__ = _get_length
1008
1009 def _get_data(self):
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001010 return self._data
Martin v. Löwis787354c2003-01-25 15:28:29 +00001011 def _set_data(self, data):
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001012 self._data = data
Martin v. Löwis787354c2003-01-25 15:28:29 +00001013
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001014 data = nodeValue = property(_get_data, _set_data)
Fred Drake87432f42001-04-04 14:09:46 +00001015
Fred Drake55c38192000-06-29 19:39:57 +00001016 def __repr__(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001017 data = self.data
1018 if len(data) > 10:
Fred Drake1f549022000-09-24 05:21:58 +00001019 dotdotdot = "..."
Fred Drake55c38192000-06-29 19:39:57 +00001020 else:
Fred Drake1f549022000-09-24 05:21:58 +00001021 dotdotdot = ""
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001022 return '<DOM %s node "%r%s">' % (
Martin v. Löwis787354c2003-01-25 15:28:29 +00001023 self.__class__.__name__, data[0:10], dotdotdot)
Fred Drake87432f42001-04-04 14:09:46 +00001024
1025 def substringData(self, offset, count):
1026 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001027 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001028 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001029 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +00001030 if count < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001031 raise xml.dom.IndexSizeErr("count cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001032 return self.data[offset:offset+count]
1033
1034 def appendData(self, arg):
1035 self.data = self.data + arg
Fred Drake87432f42001-04-04 14:09:46 +00001036
1037 def insertData(self, offset, arg):
1038 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001039 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001040 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001041 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +00001042 if arg:
1043 self.data = "%s%s%s" % (
1044 self.data[:offset], arg, self.data[offset:])
Fred Drake87432f42001-04-04 14:09:46 +00001045
1046 def deleteData(self, offset, count):
1047 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001048 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001049 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001050 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +00001051 if count < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001052 raise xml.dom.IndexSizeErr("count cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001053 if count:
1054 self.data = self.data[:offset] + self.data[offset+count:]
Fred Drake87432f42001-04-04 14:09:46 +00001055
1056 def replaceData(self, offset, count, arg):
1057 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001058 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001059 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001060 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +00001061 if count < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001062 raise xml.dom.IndexSizeErr("count cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001063 if count:
1064 self.data = "%s%s%s" % (
1065 self.data[:offset], arg, self.data[offset+count:])
Martin v. Löwis787354c2003-01-25 15:28:29 +00001066
1067defproperty(CharacterData, "length", doc="Length of the string data.")
1068
Fred Drake87432f42001-04-04 14:09:46 +00001069
1070class Text(CharacterData):
Florent Xicluna8cf4b512012-03-05 12:37:02 +01001071 __slots__ = ()
1072
Fred Drake87432f42001-04-04 14:09:46 +00001073 nodeType = Node.TEXT_NODE
1074 nodeName = "#text"
1075 attributes = None
Fred Drake55c38192000-06-29 19:39:57 +00001076
Fred Drakef7cf40d2000-12-14 18:16:11 +00001077 def splitText(self, offset):
1078 if offset < 0 or offset > len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001079 raise xml.dom.IndexSizeErr("illegal offset value")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001080 newText = self.__class__()
1081 newText.data = self.data[offset:]
1082 newText.ownerDocument = self.ownerDocument
Fred Drakef7cf40d2000-12-14 18:16:11 +00001083 next = self.nextSibling
1084 if self.parentNode and self in self.parentNode.childNodes:
1085 if next is None:
1086 self.parentNode.appendChild(newText)
1087 else:
1088 self.parentNode.insertBefore(newText, next)
1089 self.data = self.data[:offset]
1090 return newText
1091
Martin v. Löwis46fa39a2001-02-06 00:14:08 +00001092 def writexml(self, writer, indent="", addindent="", newl=""):
Ezio Melotti8008f2a2011-11-18 17:34:26 +02001093 _write_data(writer, "%s%s%s" % (indent, self.data, newl))
Fred Drake55c38192000-06-29 19:39:57 +00001094
Martin v. Löwis787354c2003-01-25 15:28:29 +00001095 # DOM Level 3 (WD 9 April 2002)
1096
1097 def _get_wholeText(self):
1098 L = [self.data]
1099 n = self.previousSibling
1100 while n is not None:
1101 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1102 L.insert(0, n.data)
1103 n = n.previousSibling
1104 else:
1105 break
1106 n = self.nextSibling
1107 while n is not None:
1108 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1109 L.append(n.data)
1110 n = n.nextSibling
1111 else:
1112 break
1113 return ''.join(L)
1114
1115 def replaceWholeText(self, content):
1116 # XXX This needs to be seriously changed if minidom ever
1117 # supports EntityReference nodes.
1118 parent = self.parentNode
1119 n = self.previousSibling
1120 while n is not None:
1121 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1122 next = n.previousSibling
1123 parent.removeChild(n)
1124 n = next
1125 else:
1126 break
1127 n = self.nextSibling
1128 if not content:
1129 parent.removeChild(self)
1130 while n is not None:
1131 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1132 next = n.nextSibling
1133 parent.removeChild(n)
1134 n = next
1135 else:
1136 break
1137 if content:
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001138 self.data = content
Martin v. Löwis787354c2003-01-25 15:28:29 +00001139 return self
1140 else:
1141 return None
1142
1143 def _get_isWhitespaceInElementContent(self):
1144 if self.data.strip():
1145 return False
1146 elem = _get_containing_element(self)
1147 if elem is None:
1148 return False
1149 info = self.ownerDocument._get_elem_info(elem)
1150 if info is None:
1151 return False
1152 else:
1153 return info.isElementContent()
1154
1155defproperty(Text, "isWhitespaceInElementContent",
1156 doc="True iff this text node contains only whitespace"
1157 " and is in element content.")
1158defproperty(Text, "wholeText",
1159 doc="The text of all logically-adjacent text nodes.")
1160
1161
1162def _get_containing_element(node):
1163 c = node.parentNode
1164 while c is not None:
1165 if c.nodeType == Node.ELEMENT_NODE:
1166 return c
1167 c = c.parentNode
1168 return None
1169
1170def _get_containing_entref(node):
1171 c = node.parentNode
1172 while c is not None:
1173 if c.nodeType == Node.ENTITY_REFERENCE_NODE:
1174 return c
1175 c = c.parentNode
1176 return None
1177
1178
Alex Martelli0ee43512006-08-21 19:53:20 +00001179class Comment(CharacterData):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001180 nodeType = Node.COMMENT_NODE
1181 nodeName = "#comment"
1182
1183 def __init__(self, data):
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001184 CharacterData.__init__(self)
1185 self._data = data
Martin v. Löwis787354c2003-01-25 15:28:29 +00001186
1187 def writexml(self, writer, indent="", addindent="", newl=""):
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001188 if "--" in self.data:
1189 raise ValueError("'--' is not allowed in a comment node")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001190 writer.write("%s<!--%s-->%s" % (indent, self.data, newl))
1191
Fred Drake87432f42001-04-04 14:09:46 +00001192
1193class CDATASection(Text):
Florent Xicluna8cf4b512012-03-05 12:37:02 +01001194 __slots__ = ()
1195
Fred Drake87432f42001-04-04 14:09:46 +00001196 nodeType = Node.CDATA_SECTION_NODE
1197 nodeName = "#cdata-section"
1198
1199 def writexml(self, writer, indent="", addindent="", newl=""):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001200 if self.data.find("]]>") >= 0:
1201 raise ValueError("']]>' not allowed in a CDATA section")
Guido van Rossum5b5e0b92001-09-19 13:28:25 +00001202 writer.write("<![CDATA[%s]]>" % self.data)
Fred Drake87432f42001-04-04 14:09:46 +00001203
1204
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001205class ReadOnlySequentialNamedNodeMap(object):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001206 __slots__ = '_seq',
1207
1208 def __init__(self, seq=()):
1209 # seq should be a list or tuple
1210 self._seq = seq
1211
1212 def __len__(self):
1213 return len(self._seq)
1214
1215 def _get_length(self):
1216 return len(self._seq)
1217
1218 def getNamedItem(self, name):
1219 for n in self._seq:
1220 if n.nodeName == name:
1221 return n
1222
1223 def getNamedItemNS(self, namespaceURI, localName):
1224 for n in self._seq:
1225 if n.namespaceURI == namespaceURI and n.localName == localName:
1226 return n
1227
1228 def __getitem__(self, name_or_tuple):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001229 if isinstance(name_or_tuple, tuple):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001230 node = self.getNamedItemNS(*name_or_tuple)
1231 else:
1232 node = self.getNamedItem(name_or_tuple)
1233 if node is None:
Collin Winter70e79802007-08-24 18:57:22 +00001234 raise KeyError(name_or_tuple)
Martin v. Löwis787354c2003-01-25 15:28:29 +00001235 return node
1236
1237 def item(self, index):
1238 if index < 0:
1239 return None
1240 try:
1241 return self._seq[index]
1242 except IndexError:
1243 return None
1244
1245 def removeNamedItem(self, name):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001246 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001247 "NamedNodeMap instance is read-only")
1248
1249 def removeNamedItemNS(self, namespaceURI, localName):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001250 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001251 "NamedNodeMap instance is read-only")
1252
1253 def setNamedItem(self, node):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001254 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001255 "NamedNodeMap instance is read-only")
1256
1257 def setNamedItemNS(self, node):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001258 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001259 "NamedNodeMap instance is read-only")
1260
1261 def __getstate__(self):
1262 return [self._seq]
1263
1264 def __setstate__(self, state):
1265 self._seq = state[0]
1266
1267defproperty(ReadOnlySequentialNamedNodeMap, "length",
1268 doc="Number of entries in the NamedNodeMap.")
Paul Prescod73678da2000-07-01 04:58:47 +00001269
Fred Drakef7cf40d2000-12-14 18:16:11 +00001270
Martin v. Löwis787354c2003-01-25 15:28:29 +00001271class Identified:
1272 """Mix-in class that supports the publicId and systemId attributes."""
1273
Florent Xicluna8cf4b512012-03-05 12:37:02 +01001274 __slots__ = 'publicId', 'systemId'
Martin v. Löwis787354c2003-01-25 15:28:29 +00001275
1276 def _identified_mixin_init(self, publicId, systemId):
1277 self.publicId = publicId
1278 self.systemId = systemId
1279
1280 def _get_publicId(self):
1281 return self.publicId
1282
1283 def _get_systemId(self):
1284 return self.systemId
1285
1286class DocumentType(Identified, Childless, Node):
Fred Drakef7cf40d2000-12-14 18:16:11 +00001287 nodeType = Node.DOCUMENT_TYPE_NODE
1288 nodeValue = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001289 name = None
1290 publicId = None
1291 systemId = None
Fred Drakedc806702001-04-05 14:41:30 +00001292 internalSubset = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001293
1294 def __init__(self, qualifiedName):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001295 self.entities = ReadOnlySequentialNamedNodeMap()
1296 self.notations = ReadOnlySequentialNamedNodeMap()
Fred Drakef7cf40d2000-12-14 18:16:11 +00001297 if qualifiedName:
1298 prefix, localname = _nssplit(qualifiedName)
1299 self.name = localname
Martin v. Löwis787354c2003-01-25 15:28:29 +00001300 self.nodeName = self.name
1301
1302 def _get_internalSubset(self):
1303 return self.internalSubset
1304
1305 def cloneNode(self, deep):
1306 if self.ownerDocument is None:
1307 # it's ok
1308 clone = DocumentType(None)
1309 clone.name = self.name
1310 clone.nodeName = self.name
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001311 operation = xml.dom.UserDataHandler.NODE_CLONED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001312 if deep:
1313 clone.entities._seq = []
1314 clone.notations._seq = []
1315 for n in self.notations._seq:
1316 notation = Notation(n.nodeName, n.publicId, n.systemId)
1317 clone.notations._seq.append(notation)
1318 n._call_user_data_handler(operation, n, notation)
1319 for e in self.entities._seq:
1320 entity = Entity(e.nodeName, e.publicId, e.systemId,
1321 e.notationName)
1322 entity.actualEncoding = e.actualEncoding
1323 entity.encoding = e.encoding
1324 entity.version = e.version
1325 clone.entities._seq.append(entity)
1326 e._call_user_data_handler(operation, n, entity)
1327 self._call_user_data_handler(operation, self, clone)
1328 return clone
1329 else:
1330 return None
1331
1332 def writexml(self, writer, indent="", addindent="", newl=""):
1333 writer.write("<!DOCTYPE ")
1334 writer.write(self.name)
1335 if self.publicId:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001336 writer.write("%s PUBLIC '%s'%s '%s'"
1337 % (newl, self.publicId, newl, self.systemId))
Martin v. Löwis787354c2003-01-25 15:28:29 +00001338 elif self.systemId:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001339 writer.write("%s SYSTEM '%s'" % (newl, self.systemId))
Martin v. Löwis787354c2003-01-25 15:28:29 +00001340 if self.internalSubset is not None:
1341 writer.write(" [")
1342 writer.write(self.internalSubset)
1343 writer.write("]")
Georg Brandl175a7dc2005-08-25 22:02:43 +00001344 writer.write(">"+newl)
Martin v. Löwis787354c2003-01-25 15:28:29 +00001345
1346class Entity(Identified, Node):
1347 attributes = None
1348 nodeType = Node.ENTITY_NODE
1349 nodeValue = None
1350
1351 actualEncoding = None
1352 encoding = None
1353 version = None
1354
1355 def __init__(self, name, publicId, systemId, notation):
1356 self.nodeName = name
1357 self.notationName = notation
1358 self.childNodes = NodeList()
1359 self._identified_mixin_init(publicId, systemId)
1360
1361 def _get_actualEncoding(self):
1362 return self.actualEncoding
1363
1364 def _get_encoding(self):
1365 return self.encoding
1366
1367 def _get_version(self):
1368 return self.version
1369
1370 def appendChild(self, newChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001371 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001372 "cannot append children to an entity node")
1373
1374 def insertBefore(self, newChild, refChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001375 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001376 "cannot insert children below an entity node")
1377
1378 def removeChild(self, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001379 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001380 "cannot remove children from an entity node")
1381
1382 def replaceChild(self, newChild, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001383 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001384 "cannot replace children of an entity node")
1385
1386class Notation(Identified, Childless, Node):
1387 nodeType = Node.NOTATION_NODE
1388 nodeValue = None
1389
1390 def __init__(self, name, publicId, systemId):
1391 self.nodeName = name
1392 self._identified_mixin_init(publicId, systemId)
Fred Drakef7cf40d2000-12-14 18:16:11 +00001393
1394
Martin v. Löwis787354c2003-01-25 15:28:29 +00001395class DOMImplementation(DOMImplementationLS):
1396 _features = [("core", "1.0"),
1397 ("core", "2.0"),
Martin v. Löwis787354c2003-01-25 15:28:29 +00001398 ("core", None),
1399 ("xml", "1.0"),
1400 ("xml", "2.0"),
Martin v. Löwis787354c2003-01-25 15:28:29 +00001401 ("xml", None),
1402 ("ls-load", "3.0"),
1403 ("ls-load", None),
1404 ]
1405
Fred Drakef7cf40d2000-12-14 18:16:11 +00001406 def hasFeature(self, feature, version):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001407 if version == "":
1408 version = None
1409 return (feature.lower(), version) in self._features
Fred Drakef7cf40d2000-12-14 18:16:11 +00001410
1411 def createDocument(self, namespaceURI, qualifiedName, doctype):
1412 if doctype and doctype.parentNode is not None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001413 raise xml.dom.WrongDocumentErr(
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +00001414 "doctype object owned by another DOM tree")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001415 doc = self._create_document()
1416
1417 add_root_element = not (namespaceURI is None
1418 and qualifiedName is None
1419 and doctype is None)
1420
1421 if not qualifiedName and add_root_element:
Martin v. Löwisb417be22001-02-06 01:16:06 +00001422 # The spec is unclear what to raise here; SyntaxErr
1423 # would be the other obvious candidate. Since Xerces raises
1424 # InvalidCharacterErr, and since SyntaxErr is not listed
1425 # for createDocument, that seems to be the better choice.
1426 # XXX: need to check for illegal characters here and in
1427 # createElement.
Martin v. Löwis787354c2003-01-25 15:28:29 +00001428
1429 # DOM Level III clears this up when talking about the return value
1430 # of this function. If namespaceURI, qName and DocType are
1431 # Null the document is returned without a document element
1432 # Otherwise if doctype or namespaceURI are not None
1433 # Then we go back to the above problem
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001434 raise xml.dom.InvalidCharacterErr("Element with no name")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001435
1436 if add_root_element:
1437 prefix, localname = _nssplit(qualifiedName)
1438 if prefix == "xml" \
1439 and namespaceURI != "http://www.w3.org/XML/1998/namespace":
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001440 raise xml.dom.NamespaceErr("illegal use of 'xml' prefix")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001441 if prefix and not namespaceURI:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001442 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001443 "illegal use of prefix without namespaces")
1444 element = doc.createElementNS(namespaceURI, qualifiedName)
1445 if doctype:
1446 doc.appendChild(doctype)
1447 doc.appendChild(element)
1448
1449 if doctype:
1450 doctype.parentNode = doctype.ownerDocument = doc
1451
Fred Drakef7cf40d2000-12-14 18:16:11 +00001452 doc.doctype = doctype
1453 doc.implementation = self
1454 return doc
1455
1456 def createDocumentType(self, qualifiedName, publicId, systemId):
1457 doctype = DocumentType(qualifiedName)
1458 doctype.publicId = publicId
1459 doctype.systemId = systemId
1460 return doctype
1461
Martin v. Löwis787354c2003-01-25 15:28:29 +00001462 # DOM Level 3 (WD 9 April 2002)
1463
1464 def getInterface(self, feature):
1465 if self.hasFeature(feature, None):
1466 return self
1467 else:
1468 return None
1469
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001470 # internal
Martin v. Löwis787354c2003-01-25 15:28:29 +00001471 def _create_document(self):
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001472 return Document()
Fred Drakef7cf40d2000-12-14 18:16:11 +00001473
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001474class ElementInfo(object):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001475 """Object that represents content-model information for an element.
1476
1477 This implementation is not expected to be used in practice; DOM
1478 builders should provide implementations which do the right thing
1479 using information available to it.
1480
1481 """
1482
1483 __slots__ = 'tagName',
1484
1485 def __init__(self, name):
1486 self.tagName = name
1487
1488 def getAttributeType(self, aname):
1489 return _no_type
1490
1491 def getAttributeTypeNS(self, namespaceURI, localName):
1492 return _no_type
1493
1494 def isElementContent(self):
1495 return False
1496
1497 def isEmpty(self):
1498 """Returns true iff this element is declared to have an EMPTY
1499 content model."""
1500 return False
1501
1502 def isId(self, aname):
Ezio Melotti42da6632011-03-15 05:18:48 +02001503 """Returns true iff the named attribute is a DTD-style ID."""
Martin v. Löwis787354c2003-01-25 15:28:29 +00001504 return False
1505
1506 def isIdNS(self, namespaceURI, localName):
1507 """Returns true iff the identified attribute is a DTD-style ID."""
1508 return False
1509
1510 def __getstate__(self):
1511 return self.tagName
1512
1513 def __setstate__(self, state):
1514 self.tagName = state
1515
1516def _clear_id_cache(node):
1517 if node.nodeType == Node.DOCUMENT_NODE:
1518 node._id_cache.clear()
1519 node._id_search_stack = None
1520 elif _in_document(node):
1521 node.ownerDocument._id_cache.clear()
1522 node.ownerDocument._id_search_stack= None
1523
1524class Document(Node, DocumentLS):
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001525 __slots__ = ('_elem_info', 'doctype',
1526 '_id_search_stack', 'childNodes', '_id_cache')
Martin v. Löwis787354c2003-01-25 15:28:29 +00001527 _child_node_types = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE,
1528 Node.COMMENT_NODE, Node.DOCUMENT_TYPE_NODE)
1529
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001530 implementation = DOMImplementation()
Fred Drake1f549022000-09-24 05:21:58 +00001531 nodeType = Node.DOCUMENT_NODE
Fred Drake4ccf4a12000-11-21 22:02:22 +00001532 nodeName = "#document"
1533 nodeValue = None
1534 attributes = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001535 parentNode = None
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001536 previousSibling = nextSibling = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001537
Martin v. Löwis787354c2003-01-25 15:28:29 +00001538
1539 # Document attributes from Level 3 (WD 9 April 2002)
1540
1541 actualEncoding = None
1542 encoding = None
1543 standalone = None
1544 version = None
1545 strictErrorChecking = False
1546 errorHandler = None
1547 documentURI = None
1548
1549 _magic_id_count = 0
1550
1551 def __init__(self):
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001552 self.doctype = None
Martin v. Löwis787354c2003-01-25 15:28:29 +00001553 self.childNodes = NodeList()
1554 # mapping of (namespaceURI, localName) -> ElementInfo
1555 # and tagName -> ElementInfo
1556 self._elem_info = {}
1557 self._id_cache = {}
1558 self._id_search_stack = None
1559
1560 def _get_elem_info(self, element):
1561 if element.namespaceURI:
1562 key = element.namespaceURI, element.localName
1563 else:
1564 key = element.tagName
1565 return self._elem_info.get(key)
1566
1567 def _get_actualEncoding(self):
1568 return self.actualEncoding
1569
1570 def _get_doctype(self):
1571 return self.doctype
1572
1573 def _get_documentURI(self):
1574 return self.documentURI
1575
1576 def _get_encoding(self):
1577 return self.encoding
1578
1579 def _get_errorHandler(self):
1580 return self.errorHandler
1581
1582 def _get_standalone(self):
1583 return self.standalone
1584
1585 def _get_strictErrorChecking(self):
1586 return self.strictErrorChecking
1587
1588 def _get_version(self):
1589 return self.version
Fred Drake55c38192000-06-29 19:39:57 +00001590
Fred Drake1f549022000-09-24 05:21:58 +00001591 def appendChild(self, node):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001592 if node.nodeType not in self._child_node_types:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001593 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001594 "%s cannot be child of %s" % (repr(node), repr(self)))
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001595 if node.parentNode is not None:
Martin v. Löwis787354c2003-01-25 15:28:29 +00001596 # This needs to be done before the next test since this
1597 # may *be* the document element, in which case it should
1598 # end up re-ordered to the end.
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001599 node.parentNode.removeChild(node)
1600
Fred Drakef7cf40d2000-12-14 18:16:11 +00001601 if node.nodeType == Node.ELEMENT_NODE \
1602 and self._get_documentElement():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001603 raise xml.dom.HierarchyRequestErr(
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +00001604 "two document elements disallowed")
Fred Drake4ccf4a12000-11-21 22:02:22 +00001605 return Node.appendChild(self, node)
Paul Prescod73678da2000-07-01 04:58:47 +00001606
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001607 def removeChild(self, oldChild):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001608 try:
1609 self.childNodes.remove(oldChild)
1610 except ValueError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001611 raise xml.dom.NotFoundErr()
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001612 oldChild.nextSibling = oldChild.previousSibling = None
1613 oldChild.parentNode = None
1614 if self.documentElement is oldChild:
1615 self.documentElement = None
Martin v. Löwis52ce0d02001-01-27 08:47:37 +00001616
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001617 return oldChild
1618
Fred Drakef7cf40d2000-12-14 18:16:11 +00001619 def _get_documentElement(self):
1620 for node in self.childNodes:
1621 if node.nodeType == Node.ELEMENT_NODE:
1622 return node
1623
1624 def unlink(self):
1625 if self.doctype is not None:
1626 self.doctype.unlink()
1627 self.doctype = None
1628 Node.unlink(self)
1629
Martin v. Löwis787354c2003-01-25 15:28:29 +00001630 def cloneNode(self, deep):
1631 if not deep:
1632 return None
1633 clone = self.implementation.createDocument(None, None, None)
1634 clone.encoding = self.encoding
1635 clone.standalone = self.standalone
1636 clone.version = self.version
1637 for n in self.childNodes:
1638 childclone = _clone_node(n, deep, clone)
1639 assert childclone.ownerDocument.isSameNode(clone)
1640 clone.childNodes.append(childclone)
1641 if childclone.nodeType == Node.DOCUMENT_NODE:
1642 assert clone.documentElement is None
1643 elif childclone.nodeType == Node.DOCUMENT_TYPE_NODE:
1644 assert clone.doctype is None
1645 clone.doctype = childclone
1646 childclone.parentNode = clone
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001647 self._call_user_data_handler(xml.dom.UserDataHandler.NODE_CLONED,
Martin v. Löwis787354c2003-01-25 15:28:29 +00001648 self, clone)
1649 return clone
1650
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001651 def createDocumentFragment(self):
1652 d = DocumentFragment()
Martin v. Löwis787354c2003-01-25 15:28:29 +00001653 d.ownerDocument = self
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001654 return d
Fred Drake55c38192000-06-29 19:39:57 +00001655
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001656 def createElement(self, tagName):
1657 e = Element(tagName)
1658 e.ownerDocument = self
1659 return e
Fred Drake55c38192000-06-29 19:39:57 +00001660
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001661 def createTextNode(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 t = Text()
1665 t.data = data
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001666 t.ownerDocument = self
1667 return t
Fred Drake55c38192000-06-29 19:39:57 +00001668
Fred Drake87432f42001-04-04 14:09:46 +00001669 def createCDATASection(self, data):
Christian Heimesc9543e42007-11-28 08:28:28 +00001670 if not isinstance(data, str):
Collin Winter70e79802007-08-24 18:57:22 +00001671 raise TypeError("node contents must be a string")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001672 c = CDATASection()
1673 c.data = data
Fred Drake87432f42001-04-04 14:09:46 +00001674 c.ownerDocument = self
1675 return c
1676
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001677 def createComment(self, data):
1678 c = Comment(data)
1679 c.ownerDocument = self
1680 return c
Fred Drake55c38192000-06-29 19:39:57 +00001681
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001682 def createProcessingInstruction(self, target, data):
1683 p = ProcessingInstruction(target, data)
1684 p.ownerDocument = self
1685 return p
1686
1687 def createAttribute(self, qName):
1688 a = Attr(qName)
1689 a.ownerDocument = self
Martin v. Löwiscb67ea12001-03-31 16:30:40 +00001690 a.value = ""
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001691 return a
Fred Drake55c38192000-06-29 19:39:57 +00001692
1693 def createElementNS(self, namespaceURI, qualifiedName):
Fred Drake4ccf4a12000-11-21 22:02:22 +00001694 prefix, localName = _nssplit(qualifiedName)
Martin v. Löwis787354c2003-01-25 15:28:29 +00001695 e = Element(qualifiedName, namespaceURI, prefix)
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001696 e.ownerDocument = self
1697 return e
Fred Drake55c38192000-06-29 19:39:57 +00001698
1699 def createAttributeNS(self, namespaceURI, qualifiedName):
Fred Drake4ccf4a12000-11-21 22:02:22 +00001700 prefix, localName = _nssplit(qualifiedName)
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001701 a = Attr(qualifiedName, namespaceURI, localName, prefix)
1702 a.ownerDocument = self
Martin v. Löwiscb67ea12001-03-31 16:30:40 +00001703 a.value = ""
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001704 return a
Fred Drake55c38192000-06-29 19:39:57 +00001705
Martin v. Löwis787354c2003-01-25 15:28:29 +00001706 # A couple of implementation-specific helpers to create node types
1707 # not supported by the W3C DOM specs:
1708
1709 def _create_entity(self, name, publicId, systemId, notationName):
1710 e = Entity(name, publicId, systemId, notationName)
1711 e.ownerDocument = self
1712 return e
1713
1714 def _create_notation(self, name, publicId, systemId):
1715 n = Notation(name, publicId, systemId)
1716 n.ownerDocument = self
1717 return n
1718
1719 def getElementById(self, id):
Guido van Rossum1b01e5c2006-08-19 02:45:06 +00001720 if id in self._id_cache:
Martin v. Löwis787354c2003-01-25 15:28:29 +00001721 return self._id_cache[id]
1722 if not (self._elem_info or self._magic_id_count):
1723 return None
1724
1725 stack = self._id_search_stack
1726 if stack is None:
1727 # we never searched before, or the cache has been cleared
1728 stack = [self.documentElement]
1729 self._id_search_stack = stack
1730 elif not stack:
1731 # Previous search was completed and cache is still valid;
1732 # no matching node.
1733 return None
1734
1735 result = None
1736 while stack:
1737 node = stack.pop()
1738 # add child elements to stack for continued searching
1739 stack.extend([child for child in node.childNodes
1740 if child.nodeType in _nodeTypes_with_children])
1741 # check this node
1742 info = self._get_elem_info(node)
1743 if info:
1744 # We have to process all ID attributes before
1745 # returning in order to get all the attributes set to
1746 # be IDs using Element.setIdAttribute*().
1747 for attr in node.attributes.values():
1748 if attr.namespaceURI:
1749 if info.isIdNS(attr.namespaceURI, attr.localName):
1750 self._id_cache[attr.value] = node
1751 if attr.value == id:
1752 result = node
1753 elif not node._magic_id_nodes:
1754 break
1755 elif info.isId(attr.name):
1756 self._id_cache[attr.value] = node
1757 if attr.value == id:
1758 result = node
1759 elif not node._magic_id_nodes:
1760 break
1761 elif attr._is_id:
1762 self._id_cache[attr.value] = node
1763 if attr.value == id:
1764 result = node
1765 elif node._magic_id_nodes == 1:
1766 break
1767 elif node._magic_id_nodes:
1768 for attr in node.attributes.values():
1769 if attr._is_id:
1770 self._id_cache[attr.value] = node
1771 if attr.value == id:
1772 result = node
1773 if result is not None:
1774 break
1775 return result
1776
Fred Drake1f549022000-09-24 05:21:58 +00001777 def getElementsByTagName(self, name):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001778 return _get_elements_by_tagName_helper(self, name, NodeList())
Fred Drakefbe7b4f2001-07-04 06:25:53 +00001779
1780 def getElementsByTagNameNS(self, namespaceURI, localName):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001781 return _get_elements_by_tagName_ns_helper(
1782 self, namespaceURI, localName, NodeList())
1783
1784 def isSupported(self, feature, version):
1785 return self.implementation.hasFeature(feature, version)
1786
1787 def importNode(self, node, deep):
1788 if node.nodeType == Node.DOCUMENT_NODE:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001789 raise xml.dom.NotSupportedErr("cannot import document nodes")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001790 elif node.nodeType == Node.DOCUMENT_TYPE_NODE:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001791 raise xml.dom.NotSupportedErr("cannot import document type nodes")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001792 return _clone_node(node, deep, self)
Fred Drake55c38192000-06-29 19:39:57 +00001793
Eli Bendersky8a805022012-07-13 09:52:39 +03001794 def writexml(self, writer, indent="", addindent="", newl="", encoding=None):
Martin v. Löwis7d650ca2002-06-30 15:05:00 +00001795 if encoding is None:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001796 writer.write('<?xml version="1.0" ?>'+newl)
Martin v. Löwis7d650ca2002-06-30 15:05:00 +00001797 else:
Eli Bendersky8a805022012-07-13 09:52:39 +03001798 writer.write('<?xml version="1.0" encoding="%s"?>%s' % (
1799 encoding, newl))
Fred Drake55c38192000-06-29 19:39:57 +00001800 for node in self.childNodes:
Martin v. Löwis46fa39a2001-02-06 00:14:08 +00001801 node.writexml(writer, indent, addindent, newl)
Fred Drake55c38192000-06-29 19:39:57 +00001802
Martin v. Löwis787354c2003-01-25 15:28:29 +00001803 # DOM Level 3 (WD 9 April 2002)
1804
1805 def renameNode(self, n, namespaceURI, name):
1806 if n.ownerDocument is not self:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001807 raise xml.dom.WrongDocumentErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001808 "cannot rename nodes from other documents;\n"
1809 "expected %s,\nfound %s" % (self, n.ownerDocument))
1810 if n.nodeType not in (Node.ELEMENT_NODE, Node.ATTRIBUTE_NODE):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001811 raise xml.dom.NotSupportedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001812 "renameNode() only applies to element and attribute nodes")
1813 if namespaceURI != EMPTY_NAMESPACE:
1814 if ':' in name:
1815 prefix, localName = name.split(':', 1)
1816 if ( prefix == "xmlns"
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001817 and namespaceURI != xml.dom.XMLNS_NAMESPACE):
1818 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001819 "illegal use of 'xmlns' prefix")
1820 else:
1821 if ( name == "xmlns"
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001822 and namespaceURI != xml.dom.XMLNS_NAMESPACE
Martin v. Löwis787354c2003-01-25 15:28:29 +00001823 and n.nodeType == Node.ATTRIBUTE_NODE):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001824 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001825 "illegal use of the 'xmlns' attribute")
1826 prefix = None
1827 localName = name
1828 else:
1829 prefix = None
1830 localName = None
1831 if n.nodeType == Node.ATTRIBUTE_NODE:
1832 element = n.ownerElement
1833 if element is not None:
1834 is_id = n._is_id
1835 element.removeAttributeNode(n)
1836 else:
1837 element = None
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001838 n.prefix = prefix
1839 n._localName = localName
1840 n.namespaceURI = namespaceURI
1841 n.nodeName = name
Martin v. Löwis787354c2003-01-25 15:28:29 +00001842 if n.nodeType == Node.ELEMENT_NODE:
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001843 n.tagName = name
Martin v. Löwis787354c2003-01-25 15:28:29 +00001844 else:
1845 # attribute node
Martin v. Löwis14aa2802012-02-19 20:25:12 +01001846 n.name = name
Martin v. Löwis787354c2003-01-25 15:28:29 +00001847 if element is not None:
1848 element.setAttributeNode(n)
1849 if is_id:
1850 element.setIdAttributeNode(n)
1851 # It's not clear from a semantic perspective whether we should
1852 # call the user data handlers for the NODE_RENAMED event since
1853 # we're re-using the existing node. The draft spec has been
1854 # interpreted as meaning "no, don't call the handler unless a
1855 # new node is created."
1856 return n
1857
1858defproperty(Document, "documentElement",
1859 doc="Top-level element of this document.")
1860
1861
1862def _clone_node(node, deep, newOwnerDocument):
1863 """
1864 Clone a node and give it the new owner document.
1865 Called by Node.cloneNode and Document.importNode
1866 """
1867 if node.ownerDocument.isSameNode(newOwnerDocument):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001868 operation = xml.dom.UserDataHandler.NODE_CLONED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001869 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001870 operation = xml.dom.UserDataHandler.NODE_IMPORTED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001871 if node.nodeType == Node.ELEMENT_NODE:
1872 clone = newOwnerDocument.createElementNS(node.namespaceURI,
1873 node.nodeName)
1874 for attr in node.attributes.values():
1875 clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value)
1876 a = clone.getAttributeNodeNS(attr.namespaceURI, attr.localName)
1877 a.specified = attr.specified
1878
1879 if deep:
1880 for child in node.childNodes:
1881 c = _clone_node(child, deep, newOwnerDocument)
1882 clone.appendChild(c)
1883
1884 elif node.nodeType == Node.DOCUMENT_FRAGMENT_NODE:
1885 clone = newOwnerDocument.createDocumentFragment()
1886 if deep:
1887 for child in node.childNodes:
1888 c = _clone_node(child, deep, newOwnerDocument)
1889 clone.appendChild(c)
1890
1891 elif node.nodeType == Node.TEXT_NODE:
1892 clone = newOwnerDocument.createTextNode(node.data)
1893 elif node.nodeType == Node.CDATA_SECTION_NODE:
1894 clone = newOwnerDocument.createCDATASection(node.data)
1895 elif node.nodeType == Node.PROCESSING_INSTRUCTION_NODE:
1896 clone = newOwnerDocument.createProcessingInstruction(node.target,
1897 node.data)
1898 elif node.nodeType == Node.COMMENT_NODE:
1899 clone = newOwnerDocument.createComment(node.data)
1900 elif node.nodeType == Node.ATTRIBUTE_NODE:
1901 clone = newOwnerDocument.createAttributeNS(node.namespaceURI,
1902 node.nodeName)
1903 clone.specified = True
1904 clone.value = node.value
1905 elif node.nodeType == Node.DOCUMENT_TYPE_NODE:
1906 assert node.ownerDocument is not newOwnerDocument
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001907 operation = xml.dom.UserDataHandler.NODE_IMPORTED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001908 clone = newOwnerDocument.implementation.createDocumentType(
1909 node.name, node.publicId, node.systemId)
1910 clone.ownerDocument = newOwnerDocument
1911 if deep:
1912 clone.entities._seq = []
1913 clone.notations._seq = []
1914 for n in node.notations._seq:
1915 notation = Notation(n.nodeName, n.publicId, n.systemId)
1916 notation.ownerDocument = newOwnerDocument
1917 clone.notations._seq.append(notation)
1918 if hasattr(n, '_call_user_data_handler'):
1919 n._call_user_data_handler(operation, n, notation)
1920 for e in node.entities._seq:
1921 entity = Entity(e.nodeName, e.publicId, e.systemId,
1922 e.notationName)
1923 entity.actualEncoding = e.actualEncoding
1924 entity.encoding = e.encoding
1925 entity.version = e.version
1926 entity.ownerDocument = newOwnerDocument
1927 clone.entities._seq.append(entity)
1928 if hasattr(e, '_call_user_data_handler'):
1929 e._call_user_data_handler(operation, n, entity)
1930 else:
1931 # Note the cloning of Document and DocumentType nodes is
Ezio Melotti13925002011-03-16 11:05:33 +02001932 # implementation specific. minidom handles those cases
Martin v. Löwis787354c2003-01-25 15:28:29 +00001933 # directly in the cloneNode() methods.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001934 raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node))
Martin v. Löwis787354c2003-01-25 15:28:29 +00001935
1936 # Check for _call_user_data_handler() since this could conceivably
1937 # used with other DOM implementations (one of the FourThought
1938 # DOMs, perhaps?).
1939 if hasattr(node, '_call_user_data_handler'):
1940 node._call_user_data_handler(operation, node, clone)
1941 return clone
1942
1943
1944def _nssplit(qualifiedName):
1945 fields = qualifiedName.split(':', 1)
1946 if len(fields) == 2:
1947 return fields
1948 else:
1949 return (None, fields[0])
1950
1951
Martin v. Löwis787354c2003-01-25 15:28:29 +00001952def _do_pulldom_parse(func, args, kwargs):
Raymond Hettingerff41c482003-04-06 09:01:11 +00001953 events = func(*args, **kwargs)
Fred Drake1f549022000-09-24 05:21:58 +00001954 toktype, rootNode = events.getEvent()
1955 events.expandNode(rootNode)
Martin v. Löwisb417be22001-02-06 01:16:06 +00001956 events.clear()
Fred Drake55c38192000-06-29 19:39:57 +00001957 return rootNode
1958
Martin v. Löwis787354c2003-01-25 15:28:29 +00001959def parse(file, parser=None, bufsize=None):
Fred Drakef7cf40d2000-12-14 18:16:11 +00001960 """Parse a file into a DOM by filename or file object."""
Martin v. Löwis787354c2003-01-25 15:28:29 +00001961 if parser is None and not bufsize:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001962 from xml.dom import expatbuilder
Martin v. Löwis787354c2003-01-25 15:28:29 +00001963 return expatbuilder.parse(file)
1964 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001965 from xml.dom import pulldom
Raymond Hettingerff41c482003-04-06 09:01:11 +00001966 return _do_pulldom_parse(pulldom.parse, (file,),
Martin v. Löwis787354c2003-01-25 15:28:29 +00001967 {'parser': parser, 'bufsize': bufsize})
Fred Drake55c38192000-06-29 19:39:57 +00001968
Martin v. Löwis787354c2003-01-25 15:28:29 +00001969def parseString(string, parser=None):
Fred Drakef7cf40d2000-12-14 18:16:11 +00001970 """Parse a file into a DOM from a string."""
Martin v. Löwis787354c2003-01-25 15:28:29 +00001971 if parser is None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001972 from xml.dom import expatbuilder
Martin v. Löwis787354c2003-01-25 15:28:29 +00001973 return expatbuilder.parseString(string)
1974 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001975 from xml.dom import pulldom
Martin v. Löwis787354c2003-01-25 15:28:29 +00001976 return _do_pulldom_parse(pulldom.parseString, (string,),
1977 {'parser': parser})
Martin v. Löwis7edbd4f2001-02-22 14:05:50 +00001978
Martin v. Löwis787354c2003-01-25 15:28:29 +00001979def getDOMImplementation(features=None):
1980 if features:
Christian Heimesc9543e42007-11-28 08:28:28 +00001981 if isinstance(features, str):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001982 features = domreg._parse_feature_string(features)
1983 for f, v in features:
1984 if not Document.implementation.hasFeature(f, v):
1985 return None
Martin v. Löwis7edbd4f2001-02-22 14:05:50 +00001986 return Document.implementation