blob: 8a84d0f38556ab15d536fdb41b843e105e27824d [file] [log] [blame]
Fred Drake1f549022000-09-24 05:21:58 +00001"""\
Fred Drakef7cf40d2000-12-14 18:16:11 +00002minidom.py -- a lightweight DOM implementation.
Fred Drake55c38192000-06-29 19:39:57 +00003
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +00004parse("foo.xml")
Paul Prescod623511b2000-07-21 22:05:49 +00005
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +00006parseString("<foo><bar/></foo>")
Paul Prescod623511b2000-07-21 22:05:49 +00007
Fred Drake55c38192000-06-29 19:39:57 +00008Todo:
9=====
10 * convenience methods for getting elements and text.
11 * more testing
12 * bring some of the writer and linearizer code into conformance with this
13 interface
14 * SAX 2 namespaces
15"""
16
Fred Drake1f549022000-09-24 05:21:58 +000017import string
Fred Drake4ccf4a12000-11-21 22:02:22 +000018_string = string
19del string
20
Andrew M. Kuchling291ed4f2000-12-31 03:50:23 +000021from xml.dom import HierarchyRequestErr
22
Fred Drake4ccf4a12000-11-21 22:02:22 +000023# localize the types, and allow support for Unicode values if available:
Fred Drake1f549022000-09-24 05:21:58 +000024import types
Fred Drake4ccf4a12000-11-21 22:02:22 +000025_TupleType = types.TupleType
26try:
27 _StringTypes = (types.StringType, types.UnicodeType)
28except AttributeError:
29 _StringTypes = (types.StringType,)
30del types
31
Fred Drakef7cf40d2000-12-14 18:16:11 +000032import xml.dom
Fred Drake55c38192000-06-29 19:39:57 +000033
Fred Drake3ac6a092001-09-28 04:33:06 +000034
35if list is type([]):
36 class NodeList(list):
Fred Drake575712e2001-09-28 20:25:45 +000037 __dynamic__ = 0
38
Fred Drake3ac6a092001-09-28 04:33:06 +000039 def item(self, index):
40 if 0 <= index < len(self):
41 return self[index]
42
Fred Drake575712e2001-09-28 20:25:45 +000043 length = property(lambda self: len(self),
44 doc="The number of nodes in the NodeList.")
Fred Drake3ac6a092001-09-28 04:33:06 +000045
46else:
47 def NodeList():
48 return []
49
50
Fred Drake575712e2001-09-28 20:25:45 +000051class Node(xml.dom.Node):
Fred Drake1f549022000-09-24 05:21:58 +000052 allnodes = {}
53 _debug = 0
54 _makeParentNodes = 1
55 debug = None
Andrew M. Kuchling291ed4f2000-12-31 03:50:23 +000056 childNodeTypes = ()
Martin v. Löwis126f2f62001-03-13 10:50:13 +000057 namespaceURI = None # this is non-null only for elements and attributes
Fred Drake575712e2001-09-28 20:25:45 +000058 parentNode = None
59 ownerDocument = None
Martin v. Löwis52ce0d02001-01-27 08:47:37 +000060
Fred Drake1f549022000-09-24 05:21:58 +000061 def __init__(self):
Fred Drake3ac6a092001-09-28 04:33:06 +000062 self.childNodes = NodeList()
Fred Drake16f63292000-10-23 18:09:50 +000063 if Node._debug:
Fred Drake1f549022000-09-24 05:21:58 +000064 index = repr(id(self)) + repr(self.__class__)
65 Node.allnodes[index] = repr(self.__dict__)
66 if Node.debug is None:
Fred Drake4ccf4a12000-11-21 22:02:22 +000067 Node.debug = _get_StringIO()
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +000068 #open("debug4.out", "w")
Fred Drake1f549022000-09-24 05:21:58 +000069 Node.debug.write("create %s\n" % index)
Fred Drake55c38192000-06-29 19:39:57 +000070
Fred Drake1f549022000-09-24 05:21:58 +000071 def __nonzero__(self):
72 return 1
Fred Drake55c38192000-06-29 19:39:57 +000073
Fred Drake1f549022000-09-24 05:21:58 +000074 def toxml(self):
Fred Drake4ccf4a12000-11-21 22:02:22 +000075 writer = _get_StringIO()
Fred Drake1f549022000-09-24 05:21:58 +000076 self.writexml(writer)
Fred Drake55c38192000-06-29 19:39:57 +000077 return writer.getvalue()
78
Martin v. Löwis46fa39a2001-02-06 00:14:08 +000079 def toprettyxml(self, indent="\t", newl="\n"):
Martin v. Löwiscb67ea12001-03-31 16:30:40 +000080 # indent = the indentation string to prepend, per level
81 # newl = the newline string to append
82 writer = _get_StringIO()
83 self.writexml(writer, "", indent, newl)
84 return writer.getvalue()
Martin v. Löwis46fa39a2001-02-06 00:14:08 +000085
Fred Drake1f549022000-09-24 05:21:58 +000086 def hasChildNodes(self):
87 if self.childNodes:
88 return 1
89 else:
90 return 0
Fred Drake55c38192000-06-29 19:39:57 +000091
Fred Drake1f549022000-09-24 05:21:58 +000092 def _get_firstChild(self):
Fred Drake4ccf4a12000-11-21 22:02:22 +000093 if self.childNodes:
94 return self.childNodes[0]
Paul Prescod73678da2000-07-01 04:58:47 +000095
Fred Drake1f549022000-09-24 05:21:58 +000096 def _get_lastChild(self):
Fred Drake4ccf4a12000-11-21 22:02:22 +000097 if self.childNodes:
98 return self.childNodes[-1]
Paul Prescod73678da2000-07-01 04:58:47 +000099
Fred Draked1572372001-09-29 04:58:32 +0000100 try:
101 property
102 except NameError:
103 def __getattr__(self, key):
104 if key[0:2] == "__":
105 raise AttributeError, key
106 # getattr should never call getattr!
107 if self.__dict__.has_key("inGetAttr"):
108 del self.inGetAttr
109 raise AttributeError, key
110
111 prefix, attrname = key[:5], key[5:]
112 if prefix == "_get_":
113 self.inGetAttr = 1
114 if hasattr(self, attrname):
115 del self.inGetAttr
116 return (lambda self=self, attrname=attrname:
117 getattr(self, attrname))
118 else:
119 del self.inGetAttr
120 raise AttributeError, key
121 else:
122 self.inGetAttr = 1
123 try:
124 func = getattr(self, "_get_" + key)
125 except AttributeError:
126 raise AttributeError, key
127 del self.inGetAttr
128 return func()
129 else:
130 firstChild = property(_get_firstChild,
131 doc="First child node, or None.")
132 lastChild = property(_get_lastChild,
133 doc="Last child node, or None.")
134
Fred Drake1f549022000-09-24 05:21:58 +0000135 def insertBefore(self, newChild, refChild):
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000136 if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE:
137 for c in newChild.childNodes:
138 self.insertBefore(c, refChild)
139 ### The DOM does not clearly specify what to return in this case
140 return newChild
Andrew M. Kuchling291ed4f2000-12-31 03:50:23 +0000141 if newChild.nodeType not in self.childNodeTypes:
142 raise HierarchyRequestErr, \
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000143 "%s cannot be child of %s" % (repr(newChild), repr(self))
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +0000144 if newChild.parentNode is not None:
145 newChild.parentNode.removeChild(newChild)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000146 if refChild is None:
147 self.appendChild(newChild)
148 else:
149 index = self.childNodes.index(refChild)
150 self.childNodes.insert(index, newChild)
151 newChild.nextSibling = refChild
152 refChild.previousSibling = newChild
153 if index:
154 node = self.childNodes[index-1]
155 node.nextSibling = newChild
156 newChild.previousSibling = node
157 else:
158 newChild.previousSibling = None
159 if self._makeParentNodes:
160 newChild.parentNode = self
161 return newChild
Fred Drake55c38192000-06-29 19:39:57 +0000162
Fred Drake1f549022000-09-24 05:21:58 +0000163 def appendChild(self, node):
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000164 if node.nodeType == self.DOCUMENT_FRAGMENT_NODE:
165 for c in node.childNodes:
166 self.appendChild(c)
167 ### The DOM does not clearly specify what to return in this case
168 return node
Andrew M. Kuchling291ed4f2000-12-31 03:50:23 +0000169 if node.nodeType not in self.childNodeTypes:
170 raise HierarchyRequestErr, \
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000171 "%s cannot be child of %s" % (repr(node), repr(self))
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +0000172 if node.parentNode is not None:
173 node.parentNode.removeChild(node)
Fred Drake13a30692000-10-09 20:04:16 +0000174 if self.childNodes:
175 last = self.lastChild
176 node.previousSibling = last
177 last.nextSibling = node
178 else:
179 node.previousSibling = None
180 node.nextSibling = None
Fred Drake1f549022000-09-24 05:21:58 +0000181 self.childNodes.append(node)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000182 if self._makeParentNodes:
183 node.parentNode = self
Paul Prescod73678da2000-07-01 04:58:47 +0000184 return node
185
Fred Drake1f549022000-09-24 05:21:58 +0000186 def replaceChild(self, newChild, oldChild):
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000187 if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE:
188 refChild = oldChild.nextSibling
189 self.removeChild(oldChild)
190 return self.insertBefore(newChild, refChild)
Andrew M. Kuchling291ed4f2000-12-31 03:50:23 +0000191 if newChild.nodeType not in self.childNodeTypes:
192 raise HierarchyRequestErr, \
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000193 "%s cannot be child of %s" % (repr(newChild), repr(self))
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +0000194 if newChild.parentNode is not None:
195 newChild.parentNode.removeChild(newChild)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000196 if newChild is oldChild:
197 return
Fred Drake1f549022000-09-24 05:21:58 +0000198 index = self.childNodes.index(oldChild)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000199 self.childNodes[index] = newChild
200 if self._makeParentNodes:
201 newChild.parentNode = self
202 oldChild.parentNode = None
203 newChild.nextSibling = oldChild.nextSibling
204 newChild.previousSibling = oldChild.previousSibling
Martin v. Löwis156c3372000-12-28 18:40:56 +0000205 oldChild.nextSibling = None
Fred Drake4ccf4a12000-11-21 22:02:22 +0000206 oldChild.previousSibling = None
Martin v. Löwis156c3372000-12-28 18:40:56 +0000207 if newChild.previousSibling:
208 newChild.previousSibling.nextSibling = newChild
209 if newChild.nextSibling:
210 newChild.nextSibling.previousSibling = newChild
Fred Drake4ccf4a12000-11-21 22:02:22 +0000211 return oldChild
Paul Prescod73678da2000-07-01 04:58:47 +0000212
Fred Drake1f549022000-09-24 05:21:58 +0000213 def removeChild(self, oldChild):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000214 self.childNodes.remove(oldChild)
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +0000215 if oldChild.nextSibling is not None:
216 oldChild.nextSibling.previousSibling = oldChild.previousSibling
217 if oldChild.previousSibling is not None:
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000218 oldChild.previousSibling.nextSibling = oldChild.nextSibling
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +0000219 oldChild.nextSibling = oldChild.previousSibling = None
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000220
Fred Drake4ccf4a12000-11-21 22:02:22 +0000221 if self._makeParentNodes:
222 oldChild.parentNode = None
223 return oldChild
224
225 def normalize(self):
Fred Drakef7cf40d2000-12-14 18:16:11 +0000226 L = []
227 for child in self.childNodes:
228 if child.nodeType == Node.TEXT_NODE:
229 data = child.data
230 if data and L and L[-1].nodeType == child.nodeType:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000231 # collapse text node
232 node = L[-1]
233 node.data = node.nodeValue = node.data + child.data
234 node.nextSibling = child.nextSibling
235 child.unlink()
Fred Drakef7cf40d2000-12-14 18:16:11 +0000236 elif data:
237 if L:
238 L[-1].nextSibling = child
239 child.previousSibling = L[-1]
240 else:
241 child.previousSibling = None
242 L.append(child)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000243 else:
Fred Drakef7cf40d2000-12-14 18:16:11 +0000244 # empty text node; discard
245 child.unlink()
246 else:
247 if L:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000248 L[-1].nextSibling = child
249 child.previousSibling = L[-1]
Fred Drakef7cf40d2000-12-14 18:16:11 +0000250 else:
251 child.previousSibling = None
252 L.append(child)
253 if child.nodeType == Node.ELEMENT_NODE:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000254 child.normalize()
Fred Drakef7cf40d2000-12-14 18:16:11 +0000255 self.childNodes[:] = L
Paul Prescod73678da2000-07-01 04:58:47 +0000256
Fred Drake1f549022000-09-24 05:21:58 +0000257 def cloneNode(self, deep):
Paul Prescod73678da2000-07-01 04:58:47 +0000258 import new
Fred Drake4ccf4a12000-11-21 22:02:22 +0000259 clone = new.instance(self.__class__, self.__dict__.copy())
260 if self._makeParentNodes:
261 clone.parentNode = None
Fred Drake3ac6a092001-09-28 04:33:06 +0000262 clone.childNodes = NodeList()
Fred Drake4ccf4a12000-11-21 22:02:22 +0000263 if deep:
264 for child in self.childNodes:
265 clone.appendChild(child.cloneNode(1))
Paul Prescod73678da2000-07-01 04:58:47 +0000266 return clone
Fred Drake55c38192000-06-29 19:39:57 +0000267
Fred Drake25239772001-02-02 19:40:19 +0000268 # DOM Level 3 (Working Draft 2001-Jan-26)
269
270 def isSameNode(self, other):
271 return self is other
272
273 # minidom-specific API:
274
Fred Drake1f549022000-09-24 05:21:58 +0000275 def unlink(self):
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000276 self.parentNode = self.ownerDocument = None
Fred Drake4ccf4a12000-11-21 22:02:22 +0000277 for child in self.childNodes:
278 child.unlink()
Fred Drake1f549022000-09-24 05:21:58 +0000279 self.childNodes = None
Paul Prescod4221ff02000-10-13 20:11:42 +0000280 self.previousSibling = None
281 self.nextSibling = None
Paul Prescod73678da2000-07-01 04:58:47 +0000282 if Node._debug:
Fred Drake1f549022000-09-24 05:21:58 +0000283 index = repr(id(self)) + repr(self.__class__)
284 self.debug.write("Deleting: %s\n" % index)
Paul Prescod73678da2000-07-01 04:58:47 +0000285 del Node.allnodes[index]
Fred Drake55c38192000-06-29 19:39:57 +0000286
Fred Drake1f549022000-09-24 05:21:58 +0000287def _write_data(writer, data):
Fred Drake55c38192000-06-29 19:39:57 +0000288 "Writes datachars to writer."
Fred Drake4ccf4a12000-11-21 22:02:22 +0000289 replace = _string.replace
290 data = replace(data, "&", "&amp;")
291 data = replace(data, "<", "&lt;")
292 data = replace(data, "\"", "&quot;")
293 data = replace(data, ">", "&gt;")
Fred Drake55c38192000-06-29 19:39:57 +0000294 writer.write(data)
295
Fred Drake1f549022000-09-24 05:21:58 +0000296def _getElementsByTagNameHelper(parent, name, rc):
Fred Drake55c38192000-06-29 19:39:57 +0000297 for node in parent.childNodes:
Fred Drake1f549022000-09-24 05:21:58 +0000298 if node.nodeType == Node.ELEMENT_NODE and \
299 (name == "*" or node.tagName == name):
300 rc.append(node)
301 _getElementsByTagNameHelper(node, name, rc)
Fred Drake55c38192000-06-29 19:39:57 +0000302 return rc
303
Fred Drake1f549022000-09-24 05:21:58 +0000304def _getElementsByTagNameNSHelper(parent, nsURI, localName, rc):
Fred Drake55c38192000-06-29 19:39:57 +0000305 for node in parent.childNodes:
Fred Drake1f549022000-09-24 05:21:58 +0000306 if node.nodeType == Node.ELEMENT_NODE:
Martin v. Löwised525fb2001-06-03 14:06:42 +0000307 if ((localName == "*" or node.localName == localName) and
Fred Drake1f549022000-09-24 05:21:58 +0000308 (nsURI == "*" or node.namespaceURI == nsURI)):
309 rc.append(node)
Fred Drakef7cf40d2000-12-14 18:16:11 +0000310 _getElementsByTagNameNSHelper(node, nsURI, localName, rc)
311 return rc
Fred Drake55c38192000-06-29 19:39:57 +0000312
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000313class DocumentFragment(Node):
314 nodeType = Node.DOCUMENT_FRAGMENT_NODE
315 nodeName = "#document-fragment"
316 nodeValue = None
317 attributes = None
318 parentNode = None
319 childNodeTypes = (Node.ELEMENT_NODE,
320 Node.TEXT_NODE,
321 Node.CDATA_SECTION_NODE,
322 Node.ENTITY_REFERENCE_NODE,
323 Node.PROCESSING_INSTRUCTION_NODE,
324 Node.COMMENT_NODE,
325 Node.NOTATION_NODE)
326
327
Fred Drake55c38192000-06-29 19:39:57 +0000328class Attr(Node):
Fred Drake1f549022000-09-24 05:21:58 +0000329 nodeType = Node.ATTRIBUTE_NODE
Fred Drake4ccf4a12000-11-21 22:02:22 +0000330 attributes = None
331 ownerElement = None
Andrew M. Kuchling291ed4f2000-12-31 03:50:23 +0000332 childNodeTypes = (Node.TEXT_NODE, Node.ENTITY_REFERENCE_NODE)
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000333
Fred Drake1f549022000-09-24 05:21:58 +0000334 def __init__(self, qName, namespaceURI="", localName=None, prefix=None):
Fred Drake55c38192000-06-29 19:39:57 +0000335 # skip setattr for performance
Fred Drake4ccf4a12000-11-21 22:02:22 +0000336 d = self.__dict__
337 d["localName"] = localName or qName
338 d["nodeName"] = d["name"] = qName
339 d["namespaceURI"] = namespaceURI
340 d["prefix"] = prefix
Fred Drake1f549022000-09-24 05:21:58 +0000341 Node.__init__(self)
Paul Prescod73678da2000-07-01 04:58:47 +0000342 # nodeValue and value are set elsewhere
Fred Drake55c38192000-06-29 19:39:57 +0000343
Fred Drake1f549022000-09-24 05:21:58 +0000344 def __setattr__(self, name, value):
Fred Drakef7cf40d2000-12-14 18:16:11 +0000345 d = self.__dict__
Fred Drake1f549022000-09-24 05:21:58 +0000346 if name in ("value", "nodeValue"):
Fred Drakef7cf40d2000-12-14 18:16:11 +0000347 d["value"] = d["nodeValue"] = value
348 elif name in ("name", "nodeName"):
349 d["name"] = d["nodeName"] = value
Fred Drake55c38192000-06-29 19:39:57 +0000350 else:
Fred Drakef7cf40d2000-12-14 18:16:11 +0000351 d[name] = value
Fred Drake55c38192000-06-29 19:39:57 +0000352
Fred Drake4ccf4a12000-11-21 22:02:22 +0000353 def cloneNode(self, deep):
354 clone = Node.cloneNode(self, deep)
355 if clone.__dict__.has_key("ownerElement"):
356 del clone.ownerElement
357 return clone
358
Fred Drakef7cf40d2000-12-14 18:16:11 +0000359
360class NamedNodeMap:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000361 """The attribute list is a transient interface to the underlying
362 dictionaries. Mutations here will change the underlying element's
Fred Drakef7cf40d2000-12-14 18:16:11 +0000363 dictionary.
364
365 Ordering is imposed artificially and does not reflect the order of
366 attributes as found in an input document.
367 """
Fred Drake4ccf4a12000-11-21 22:02:22 +0000368
Fred Drake1f549022000-09-24 05:21:58 +0000369 def __init__(self, attrs, attrsNS):
370 self._attrs = attrs
371 self._attrsNS = attrsNS
Fred Drakef7cf40d2000-12-14 18:16:11 +0000372
Fred Draked1572372001-09-29 04:58:32 +0000373 try:
374 property
375 except NameError:
376 def __getattr__(self, name):
377 if name == "length":
378 return len(self._attrs)
379 raise AttributeError, name
380 else:
381 length = property(lambda self: len(self._attrs),
382 doc="Number of nodes in the NamedNodeMap.")
Fred Drake55c38192000-06-29 19:39:57 +0000383
Fred Drake1f549022000-09-24 05:21:58 +0000384 def item(self, index):
Fred Drake55c38192000-06-29 19:39:57 +0000385 try:
Fred Drakef7cf40d2000-12-14 18:16:11 +0000386 return self[self._attrs.keys()[index]]
Fred Drake55c38192000-06-29 19:39:57 +0000387 except IndexError:
388 return None
Fred Drake55c38192000-06-29 19:39:57 +0000389
Fred Drake1f549022000-09-24 05:21:58 +0000390 def items(self):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000391 L = []
392 for node in self._attrs.values():
Martin v. Löwisd5fb58f2001-01-27 08:38:34 +0000393 L.append((node.nodeName, node.value))
Fred Drake4ccf4a12000-11-21 22:02:22 +0000394 return L
Fred Drake1f549022000-09-24 05:21:58 +0000395
396 def itemsNS(self):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000397 L = []
398 for node in self._attrs.values():
399 L.append(((node.URI, node.localName), node.value))
400 return L
Fred Drake16f63292000-10-23 18:09:50 +0000401
Fred Drake1f549022000-09-24 05:21:58 +0000402 def keys(self):
Paul Prescod73678da2000-07-01 04:58:47 +0000403 return self._attrs.keys()
Fred Drake55c38192000-06-29 19:39:57 +0000404
Fred Drake1f549022000-09-24 05:21:58 +0000405 def keysNS(self):
Paul Prescod73678da2000-07-01 04:58:47 +0000406 return self._attrsNS.keys()
Fred Drake55c38192000-06-29 19:39:57 +0000407
Fred Drake1f549022000-09-24 05:21:58 +0000408 def values(self):
Paul Prescod73678da2000-07-01 04:58:47 +0000409 return self._attrs.values()
Fred Drake55c38192000-06-29 19:39:57 +0000410
Martin v. Löwisd5fb58f2001-01-27 08:38:34 +0000411 def get(self, name, value = None):
412 return self._attrs.get(name, value)
413
Fred Drake1f549022000-09-24 05:21:58 +0000414 def __len__(self):
Fred Drake55c38192000-06-29 19:39:57 +0000415 return self.length
416
Fred Drake1f549022000-09-24 05:21:58 +0000417 def __cmp__(self, other):
418 if self._attrs is getattr(other, "_attrs", None):
Fred Drake55c38192000-06-29 19:39:57 +0000419 return 0
Fred Drake16f63292000-10-23 18:09:50 +0000420 else:
Fred Drake1f549022000-09-24 05:21:58 +0000421 return cmp(id(self), id(other))
Fred Drake55c38192000-06-29 19:39:57 +0000422
423 #FIXME: is it appropriate to return .value?
Fred Drake1f549022000-09-24 05:21:58 +0000424 def __getitem__(self, attname_or_tuple):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000425 if type(attname_or_tuple) is _TupleType:
Paul Prescod73678da2000-07-01 04:58:47 +0000426 return self._attrsNS[attname_or_tuple]
Fred Drake55c38192000-06-29 19:39:57 +0000427 else:
Paul Prescod73678da2000-07-01 04:58:47 +0000428 return self._attrs[attname_or_tuple]
Fred Drake55c38192000-06-29 19:39:57 +0000429
Paul Prescod1e688272000-07-01 19:21:47 +0000430 # same as set
Fred Drake1f549022000-09-24 05:21:58 +0000431 def __setitem__(self, attname, value):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000432 if type(value) in _StringTypes:
Fred Drake1f549022000-09-24 05:21:58 +0000433 node = Attr(attname)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000434 node.value = value
Paul Prescod1e688272000-07-01 19:21:47 +0000435 else:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000436 if not isinstance(value, Attr):
437 raise TypeError, "value must be a string or Attr object"
Fred Drake1f549022000-09-24 05:21:58 +0000438 node = value
Fred Drakef7cf40d2000-12-14 18:16:11 +0000439 self.setNamedItem(node)
440
441 def setNamedItem(self, node):
Andrew M. Kuchlingbc8f72c2001-02-21 01:30:26 +0000442 if not isinstance(node, Attr):
443 raise HierarchyRequestErr, \
444 "%s cannot be child of %s" % (repr(node), repr(self))
Fred Drakef7cf40d2000-12-14 18:16:11 +0000445 old = self._attrs.get(node.name)
Paul Prescod1e688272000-07-01 19:21:47 +0000446 if old:
447 old.unlink()
Fred Drake1f549022000-09-24 05:21:58 +0000448 self._attrs[node.name] = node
449 self._attrsNS[(node.namespaceURI, node.localName)] = node
Fred Drakef7cf40d2000-12-14 18:16:11 +0000450 return old
451
452 def setNamedItemNS(self, node):
453 return self.setNamedItem(node)
Paul Prescod73678da2000-07-01 04:58:47 +0000454
Fred Drake1f549022000-09-24 05:21:58 +0000455 def __delitem__(self, attname_or_tuple):
456 node = self[attname_or_tuple]
Paul Prescod73678da2000-07-01 04:58:47 +0000457 node.unlink()
458 del self._attrs[node.name]
459 del self._attrsNS[(node.namespaceURI, node.localName)]
Fred Drakef7cf40d2000-12-14 18:16:11 +0000460 self.length = len(self._attrs)
461
462AttributeList = NamedNodeMap
463
Fred Drake1f549022000-09-24 05:21:58 +0000464
Martin v. Löwisa2fda0d2000-10-07 12:10:28 +0000465class Element(Node):
Fred Drake1f549022000-09-24 05:21:58 +0000466 nodeType = Node.ELEMENT_NODE
Fred Drake4ccf4a12000-11-21 22:02:22 +0000467 nextSibling = None
468 previousSibling = None
Andrew M. Kuchling291ed4f2000-12-31 03:50:23 +0000469 childNodeTypes = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE,
470 Node.COMMENT_NODE, Node.TEXT_NODE,
471 Node.CDATA_SECTION_NODE, Node.ENTITY_REFERENCE_NODE)
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000472
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000473 def __init__(self, tagName, namespaceURI=None, prefix="",
Fred Drake1f549022000-09-24 05:21:58 +0000474 localName=None):
475 Node.__init__(self)
Fred Drake55c38192000-06-29 19:39:57 +0000476 self.tagName = self.nodeName = tagName
Fred Drake1f549022000-09-24 05:21:58 +0000477 self.localName = localName or tagName
478 self.prefix = prefix
479 self.namespaceURI = namespaceURI
480 self.nodeValue = None
Fred Drake55c38192000-06-29 19:39:57 +0000481
Fred Drake4ccf4a12000-11-21 22:02:22 +0000482 self._attrs = {} # attributes are double-indexed:
483 self._attrsNS = {} # tagName -> Attribute
484 # URI,localName -> Attribute
485 # in the future: consider lazy generation
486 # of attribute objects this is too tricky
487 # for now because of headaches with
488 # namespaces.
489
490 def cloneNode(self, deep):
491 clone = Node.cloneNode(self, deep)
492 clone._attrs = {}
493 clone._attrsNS = {}
494 for attr in self._attrs.values():
495 node = attr.cloneNode(1)
496 clone._attrs[node.name] = node
497 clone._attrsNS[(node.namespaceURI, node.localName)] = node
498 node.ownerElement = clone
499 return clone
500
501 def unlink(self):
502 for attr in self._attrs.values():
503 attr.unlink()
504 self._attrs = None
505 self._attrsNS = None
506 Node.unlink(self)
Fred Drake55c38192000-06-29 19:39:57 +0000507
Fred Drake1f549022000-09-24 05:21:58 +0000508 def getAttribute(self, attname):
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000509 try:
510 return self._attrs[attname].value
511 except KeyError:
512 return ""
Fred Drake55c38192000-06-29 19:39:57 +0000513
Fred Drake1f549022000-09-24 05:21:58 +0000514 def getAttributeNS(self, namespaceURI, localName):
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000515 try:
516 return self._attrsNS[(namespaceURI, localName)].value
517 except KeyError:
518 return ""
Fred Drake1f549022000-09-24 05:21:58 +0000519
520 def setAttribute(self, attname, value):
521 attr = Attr(attname)
Fred Drake55c38192000-06-29 19:39:57 +0000522 # for performance
Fred Drake1f549022000-09-24 05:21:58 +0000523 attr.__dict__["value"] = attr.__dict__["nodeValue"] = value
524 self.setAttributeNode(attr)
Fred Drake55c38192000-06-29 19:39:57 +0000525
Fred Drake1f549022000-09-24 05:21:58 +0000526 def setAttributeNS(self, namespaceURI, qualifiedName, value):
527 prefix, localname = _nssplit(qualifiedName)
Fred Drake55c38192000-06-29 19:39:57 +0000528 # for performance
Fred Drake1f549022000-09-24 05:21:58 +0000529 attr = Attr(qualifiedName, namespaceURI, localname, prefix)
530 attr.__dict__["value"] = attr.__dict__["nodeValue"] = value
531 self.setAttributeNode(attr)
Fred Drake55c38192000-06-29 19:39:57 +0000532
Fred Drake1f549022000-09-24 05:21:58 +0000533 def getAttributeNode(self, attrname):
534 return self._attrs.get(attrname)
Paul Prescod73678da2000-07-01 04:58:47 +0000535
Fred Drake1f549022000-09-24 05:21:58 +0000536 def getAttributeNodeNS(self, namespaceURI, localName):
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000537 return self._attrsNS.get((namespaceURI, localName))
Paul Prescod73678da2000-07-01 04:58:47 +0000538
Fred Drake1f549022000-09-24 05:21:58 +0000539 def setAttributeNode(self, attr):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000540 if attr.ownerElement not in (None, self):
Martin v. Löwisd5fb58f2001-01-27 08:38:34 +0000541 raise xml.dom.InuseAttributeErr("attribute node already owned")
Fred Drake1f549022000-09-24 05:21:58 +0000542 old = self._attrs.get(attr.name, None)
Paul Prescod73678da2000-07-01 04:58:47 +0000543 if old:
544 old.unlink()
Fred Drake1f549022000-09-24 05:21:58 +0000545 self._attrs[attr.name] = attr
546 self._attrsNS[(attr.namespaceURI, attr.localName)] = attr
Fred Drake4ccf4a12000-11-21 22:02:22 +0000547
548 # This creates a circular reference, but Element.unlink()
549 # breaks the cycle since the references to the attribute
550 # dictionaries are tossed.
551 attr.ownerElement = self
552
553 if old is not attr:
554 # It might have already been part of this node, in which case
555 # it doesn't represent a change, and should not be returned.
556 return old
Fred Drake55c38192000-06-29 19:39:57 +0000557
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000558 setAttributeNodeNS = setAttributeNode
559
Fred Drake1f549022000-09-24 05:21:58 +0000560 def removeAttribute(self, name):
Paul Prescod73678da2000-07-01 04:58:47 +0000561 attr = self._attrs[name]
Fred Drake1f549022000-09-24 05:21:58 +0000562 self.removeAttributeNode(attr)
Fred Drake55c38192000-06-29 19:39:57 +0000563
Fred Drake1f549022000-09-24 05:21:58 +0000564 def removeAttributeNS(self, namespaceURI, localName):
Paul Prescod73678da2000-07-01 04:58:47 +0000565 attr = self._attrsNS[(namespaceURI, localName)]
Fred Drake1f549022000-09-24 05:21:58 +0000566 self.removeAttributeNode(attr)
Fred Drake55c38192000-06-29 19:39:57 +0000567
Fred Drake1f549022000-09-24 05:21:58 +0000568 def removeAttributeNode(self, node):
Paul Prescod73678da2000-07-01 04:58:47 +0000569 node.unlink()
570 del self._attrs[node.name]
571 del self._attrsNS[(node.namespaceURI, node.localName)]
Fred Drake16f63292000-10-23 18:09:50 +0000572
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000573 removeAttributeNodeNS = removeAttributeNode
574
Martin v. Löwis156c3372000-12-28 18:40:56 +0000575 def hasAttribute(self, name):
576 return self._attrs.has_key(name)
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000577
Martin v. Löwis156c3372000-12-28 18:40:56 +0000578 def hasAttributeNS(self, namespaceURI, localName):
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000579 return self._attrsNS.has_key((namespaceURI, localName))
580
Fred Drake1f549022000-09-24 05:21:58 +0000581 def getElementsByTagName(self, name):
582 return _getElementsByTagNameHelper(self, name, [])
Fred Drake55c38192000-06-29 19:39:57 +0000583
Fred Drake1f549022000-09-24 05:21:58 +0000584 def getElementsByTagNameNS(self, namespaceURI, localName):
Fred Drakefbe7b4f2001-07-04 06:25:53 +0000585 return _getElementsByTagNameNSHelper(self, namespaceURI, localName, [])
Fred Drake55c38192000-06-29 19:39:57 +0000586
Fred Drake1f549022000-09-24 05:21:58 +0000587 def __repr__(self):
588 return "<DOM Element: %s at %s>" % (self.tagName, id(self))
Fred Drake55c38192000-06-29 19:39:57 +0000589
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000590 def writexml(self, writer, indent="", addindent="", newl=""):
591 # indent = current indentation
592 # addindent = indentation to add to higher levels
593 # newl = newline string
594 writer.write(indent+"<" + self.tagName)
Fred Drake16f63292000-10-23 18:09:50 +0000595
Fred Drake4ccf4a12000-11-21 22:02:22 +0000596 attrs = self._get_attributes()
597 a_names = attrs.keys()
Fred Drake55c38192000-06-29 19:39:57 +0000598 a_names.sort()
599
600 for a_name in a_names:
Fred Drake1f549022000-09-24 05:21:58 +0000601 writer.write(" %s=\"" % a_name)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000602 _write_data(writer, attrs[a_name].value)
Fred Drake55c38192000-06-29 19:39:57 +0000603 writer.write("\"")
604 if self.childNodes:
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000605 writer.write(">%s"%(newl))
Fred Drake55c38192000-06-29 19:39:57 +0000606 for node in self.childNodes:
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000607 node.writexml(writer,indent+addindent,addindent,newl)
608 writer.write("%s</%s>%s" % (indent,self.tagName,newl))
Fred Drake55c38192000-06-29 19:39:57 +0000609 else:
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000610 writer.write("/>%s"%(newl))
Fred Drake55c38192000-06-29 19:39:57 +0000611
Fred Drake1f549022000-09-24 05:21:58 +0000612 def _get_attributes(self):
613 return AttributeList(self._attrs, self._attrsNS)
Fred Drake55c38192000-06-29 19:39:57 +0000614
Fred Draked1572372001-09-29 04:58:32 +0000615 try:
616 property
617 except NameError:
618 pass
619 else:
620 attributes = property(_get_attributes,
621 doc="NamedNodeMap of attributes on the element.")
622
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000623 def hasAttributes(self):
624 if self._attrs or self._attrsNS:
625 return 1
626 else:
627 return 0
628
Fred Drake1f549022000-09-24 05:21:58 +0000629class Comment(Node):
630 nodeType = Node.COMMENT_NODE
Fred Drake4ccf4a12000-11-21 22:02:22 +0000631 nodeName = "#comment"
632 attributes = None
Andrew M. Kuchling291ed4f2000-12-31 03:50:23 +0000633 childNodeTypes = ()
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000634
Fred Drake1f549022000-09-24 05:21:58 +0000635 def __init__(self, data):
636 Node.__init__(self)
637 self.data = self.nodeValue = data
Fred Drake55c38192000-06-29 19:39:57 +0000638
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000639 def writexml(self, writer, indent="", addindent="", newl=""):
640 writer.write("%s<!--%s-->%s" % (indent,self.data,newl))
Fred Drake1f549022000-09-24 05:21:58 +0000641
642class ProcessingInstruction(Node):
643 nodeType = Node.PROCESSING_INSTRUCTION_NODE
Fred Drake4ccf4a12000-11-21 22:02:22 +0000644 attributes = None
Andrew M. Kuchling291ed4f2000-12-31 03:50:23 +0000645 childNodeTypes = ()
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000646
Fred Drake1f549022000-09-24 05:21:58 +0000647 def __init__(self, target, data):
648 Node.__init__(self)
Fred Drake55c38192000-06-29 19:39:57 +0000649 self.target = self.nodeName = target
650 self.data = self.nodeValue = data
Fred Drake55c38192000-06-29 19:39:57 +0000651
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000652 def writexml(self, writer, indent="", addindent="", newl=""):
653 writer.write("%s<?%s %s?>%s" % (indent,self.target, self.data, newl))
Fred Drake55c38192000-06-29 19:39:57 +0000654
Fred Drake87432f42001-04-04 14:09:46 +0000655class CharacterData(Node):
Fred Drake1f549022000-09-24 05:21:58 +0000656 def __init__(self, data):
Fred Drakedaa823a2001-01-08 04:04:34 +0000657 if type(data) not in _StringTypes:
658 raise TypeError, "node contents must be a string"
Fred Drake1f549022000-09-24 05:21:58 +0000659 Node.__init__(self)
Fred Drake55c38192000-06-29 19:39:57 +0000660 self.data = self.nodeValue = data
Fred Drake33d2b842001-04-04 15:15:18 +0000661 self.length = len(data)
Fred Drake87432f42001-04-04 14:09:46 +0000662
Fred Drake55c38192000-06-29 19:39:57 +0000663 def __repr__(self):
Fred Drake1f549022000-09-24 05:21:58 +0000664 if len(self.data) > 10:
665 dotdotdot = "..."
Fred Drake55c38192000-06-29 19:39:57 +0000666 else:
Fred Drake1f549022000-09-24 05:21:58 +0000667 dotdotdot = ""
Fred Drake87432f42001-04-04 14:09:46 +0000668 return "<DOM %s node \"%s%s\">" % (
669 self.__class__.__name__, self.data[0:10], dotdotdot)
670
671 def substringData(self, offset, count):
672 if offset < 0:
673 raise xml.dom.IndexSizeErr("offset cannot be negative")
674 if offset >= len(self.data):
675 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
676 if count < 0:
677 raise xml.dom.IndexSizeErr("count cannot be negative")
678 return self.data[offset:offset+count]
679
680 def appendData(self, arg):
681 self.data = self.data + arg
682 self.nodeValue = self.data
Fred Drake33d2b842001-04-04 15:15:18 +0000683 self.length = len(self.data)
Fred Drake87432f42001-04-04 14:09:46 +0000684
685 def insertData(self, offset, arg):
686 if offset < 0:
687 raise xml.dom.IndexSizeErr("offset cannot be negative")
688 if offset >= len(self.data):
689 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
690 if arg:
691 self.data = "%s%s%s" % (
692 self.data[:offset], arg, self.data[offset:])
693 self.nodeValue = self.data
Fred Drake33d2b842001-04-04 15:15:18 +0000694 self.length = len(self.data)
Fred Drake87432f42001-04-04 14:09:46 +0000695
696 def deleteData(self, offset, count):
697 if offset < 0:
698 raise xml.dom.IndexSizeErr("offset cannot be negative")
699 if offset >= len(self.data):
700 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
701 if count < 0:
702 raise xml.dom.IndexSizeErr("count cannot be negative")
703 if count:
704 self.data = self.data[:offset] + self.data[offset+count:]
705 self.nodeValue = self.data
Fred Drake33d2b842001-04-04 15:15:18 +0000706 self.length = len(self.data)
Fred Drake87432f42001-04-04 14:09:46 +0000707
708 def replaceData(self, offset, count, arg):
709 if offset < 0:
710 raise xml.dom.IndexSizeErr("offset cannot be negative")
711 if offset >= len(self.data):
712 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
713 if count < 0:
714 raise xml.dom.IndexSizeErr("count cannot be negative")
715 if count:
716 self.data = "%s%s%s" % (
717 self.data[:offset], arg, self.data[offset+count:])
718 self.nodeValue = self.data
Fred Drake33d2b842001-04-04 15:15:18 +0000719 self.length = len(self.data)
Fred Drake87432f42001-04-04 14:09:46 +0000720
721class Text(CharacterData):
722 nodeType = Node.TEXT_NODE
723 nodeName = "#text"
724 attributes = None
725 childNodeTypes = ()
Fred Drake55c38192000-06-29 19:39:57 +0000726
Fred Drakef7cf40d2000-12-14 18:16:11 +0000727 def splitText(self, offset):
728 if offset < 0 or offset > len(self.data):
Martin v. Löwisd5fb58f2001-01-27 08:38:34 +0000729 raise xml.dom.IndexSizeErr("illegal offset value")
Fred Drakef7cf40d2000-12-14 18:16:11 +0000730 newText = Text(self.data[offset:])
731 next = self.nextSibling
732 if self.parentNode and self in self.parentNode.childNodes:
733 if next is None:
734 self.parentNode.appendChild(newText)
735 else:
736 self.parentNode.insertBefore(newText, next)
737 self.data = self.data[:offset]
Fred Drake33d2b842001-04-04 15:15:18 +0000738 self.nodeValue = self.data
739 self.length = len(self.data)
Fred Drakef7cf40d2000-12-14 18:16:11 +0000740 return newText
741
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000742 def writexml(self, writer, indent="", addindent="", newl=""):
743 _write_data(writer, "%s%s%s"%(indent, self.data, newl))
Fred Drake55c38192000-06-29 19:39:57 +0000744
Fred Drake87432f42001-04-04 14:09:46 +0000745
746class CDATASection(Text):
747 nodeType = Node.CDATA_SECTION_NODE
748 nodeName = "#cdata-section"
749
750 def writexml(self, writer, indent="", addindent="", newl=""):
Guido van Rossum5b5e0b92001-09-19 13:28:25 +0000751 writer.write("<![CDATA[%s]]>" % self.data)
Fred Drake87432f42001-04-04 14:09:46 +0000752
753
Fred Drake1f549022000-09-24 05:21:58 +0000754def _nssplit(qualifiedName):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000755 fields = _string.split(qualifiedName, ':', 1)
Paul Prescod73678da2000-07-01 04:58:47 +0000756 if len(fields) == 2:
757 return fields
758 elif len(fields) == 1:
Fred Drake1f549022000-09-24 05:21:58 +0000759 return ('', fields[0])
Paul Prescod73678da2000-07-01 04:58:47 +0000760
Fred Drakef7cf40d2000-12-14 18:16:11 +0000761
762class DocumentType(Node):
763 nodeType = Node.DOCUMENT_TYPE_NODE
764 nodeValue = None
765 attributes = None
766 name = None
767 publicId = None
768 systemId = None
Fred Drakedc806702001-04-05 14:41:30 +0000769 internalSubset = None
Fred Drakef7cf40d2000-12-14 18:16:11 +0000770 entities = None
771 notations = None
772
773 def __init__(self, qualifiedName):
774 Node.__init__(self)
775 if qualifiedName:
776 prefix, localname = _nssplit(qualifiedName)
777 self.name = localname
778
779
780class DOMImplementation:
781 def hasFeature(self, feature, version):
782 if version not in ("1.0", "2.0"):
783 return 0
784 feature = _string.lower(feature)
785 return feature == "core"
786
787 def createDocument(self, namespaceURI, qualifiedName, doctype):
788 if doctype and doctype.parentNode is not None:
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000789 raise xml.dom.WrongDocumentErr(
790 "doctype object owned by another DOM tree")
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000791 doc = self._createDocument()
Fred Drakef7cf40d2000-12-14 18:16:11 +0000792 if doctype is None:
793 doctype = self.createDocumentType(qualifiedName, None, None)
Martin v. Löwisb417be22001-02-06 01:16:06 +0000794 if not qualifiedName:
795 # The spec is unclear what to raise here; SyntaxErr
796 # would be the other obvious candidate. Since Xerces raises
797 # InvalidCharacterErr, and since SyntaxErr is not listed
798 # for createDocument, that seems to be the better choice.
799 # XXX: need to check for illegal characters here and in
800 # createElement.
801 raise xml.dom.InvalidCharacterErr("Element with no name")
802 prefix, localname = _nssplit(qualifiedName)
803 if prefix == "xml" \
804 and namespaceURI != "http://www.w3.org/XML/1998/namespace":
805 raise xml.dom.NamespaceErr("illegal use of 'xml' prefix")
806 if prefix and not namespaceURI:
807 raise xml.dom.NamespaceErr(
808 "illegal use of prefix without namespaces")
809 element = doc.createElementNS(namespaceURI, qualifiedName)
810 doc.appendChild(element)
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000811 doctype.parentNode = doctype.ownerDocument = doc
Fred Drakef7cf40d2000-12-14 18:16:11 +0000812 doc.doctype = doctype
813 doc.implementation = self
814 return doc
815
816 def createDocumentType(self, qualifiedName, publicId, systemId):
817 doctype = DocumentType(qualifiedName)
818 doctype.publicId = publicId
819 doctype.systemId = systemId
820 return doctype
821
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000822 # internal
823 def _createDocument(self):
824 return Document()
Fred Drakef7cf40d2000-12-14 18:16:11 +0000825
Fred Drake1f549022000-09-24 05:21:58 +0000826class Document(Node):
827 nodeType = Node.DOCUMENT_NODE
Fred Drake4ccf4a12000-11-21 22:02:22 +0000828 nodeName = "#document"
829 nodeValue = None
830 attributes = None
Fred Drakef7cf40d2000-12-14 18:16:11 +0000831 doctype = None
832 parentNode = None
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000833 previousSibling = nextSibling = None
Fred Drakef7cf40d2000-12-14 18:16:11 +0000834
835 implementation = DOMImplementation()
Andrew M. Kuchling291ed4f2000-12-31 03:50:23 +0000836 childNodeTypes = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE,
837 Node.COMMENT_NODE, Node.DOCUMENT_TYPE_NODE)
Fred Drake55c38192000-06-29 19:39:57 +0000838
Fred Drake1f549022000-09-24 05:21:58 +0000839 def appendChild(self, node):
Andrew M. Kuchling291ed4f2000-12-31 03:50:23 +0000840 if node.nodeType not in self.childNodeTypes:
841 raise HierarchyRequestErr, \
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000842 "%s cannot be child of %s" % (repr(node), repr(self))
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +0000843 if node.parentNode is not None:
844 node.parentNode.removeChild(node)
845
Fred Drakef7cf40d2000-12-14 18:16:11 +0000846 if node.nodeType == Node.ELEMENT_NODE \
847 and self._get_documentElement():
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000848 raise xml.dom.HierarchyRequestErr(
849 "two document elements disallowed")
Fred Drake4ccf4a12000-11-21 22:02:22 +0000850 return Node.appendChild(self, node)
Paul Prescod73678da2000-07-01 04:58:47 +0000851
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +0000852 def removeChild(self, oldChild):
853 self.childNodes.remove(oldChild)
854 oldChild.nextSibling = oldChild.previousSibling = None
855 oldChild.parentNode = None
856 if self.documentElement is oldChild:
857 self.documentElement = None
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000858
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +0000859 return oldChild
860
Fred Drakef7cf40d2000-12-14 18:16:11 +0000861 def _get_documentElement(self):
862 for node in self.childNodes:
863 if node.nodeType == Node.ELEMENT_NODE:
864 return node
865
Fred Draked1572372001-09-29 04:58:32 +0000866 try:
867 property
868 except NameError:
869 pass
870 else:
871 documentElement = property(_get_documentElement,
872 doc="Top-level element of this document.")
873
Fred Drakef7cf40d2000-12-14 18:16:11 +0000874 def unlink(self):
875 if self.doctype is not None:
876 self.doctype.unlink()
877 self.doctype = None
878 Node.unlink(self)
879
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000880 def createDocumentFragment(self):
881 d = DocumentFragment()
882 d.ownerDoc = self
883 return d
Fred Drake55c38192000-06-29 19:39:57 +0000884
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000885 def createElement(self, tagName):
886 e = Element(tagName)
887 e.ownerDocument = self
888 return e
Fred Drake55c38192000-06-29 19:39:57 +0000889
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000890 def createTextNode(self, data):
891 t = Text(data)
892 t.ownerDocument = self
893 return t
Fred Drake55c38192000-06-29 19:39:57 +0000894
Fred Drake87432f42001-04-04 14:09:46 +0000895 def createCDATASection(self, data):
896 c = CDATASection(data)
897 c.ownerDocument = self
898 return c
899
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000900 def createComment(self, data):
901 c = Comment(data)
902 c.ownerDocument = self
903 return c
Fred Drake55c38192000-06-29 19:39:57 +0000904
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000905 def createProcessingInstruction(self, target, data):
906 p = ProcessingInstruction(target, data)
907 p.ownerDocument = self
908 return p
909
910 def createAttribute(self, qName):
911 a = Attr(qName)
912 a.ownerDocument = self
Martin v. Löwiscb67ea12001-03-31 16:30:40 +0000913 a.value = ""
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000914 return a
Fred Drake55c38192000-06-29 19:39:57 +0000915
916 def createElementNS(self, namespaceURI, qualifiedName):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000917 prefix, localName = _nssplit(qualifiedName)
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000918 e = Element(qualifiedName, namespaceURI, prefix, localName)
919 e.ownerDocument = self
920 return e
Fred Drake55c38192000-06-29 19:39:57 +0000921
922 def createAttributeNS(self, namespaceURI, qualifiedName):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000923 prefix, localName = _nssplit(qualifiedName)
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000924 a = Attr(qualifiedName, namespaceURI, localName, prefix)
925 a.ownerDocument = self
Martin v. Löwiscb67ea12001-03-31 16:30:40 +0000926 a.value = ""
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000927 return a
Fred Drake55c38192000-06-29 19:39:57 +0000928
Fred Drake1f549022000-09-24 05:21:58 +0000929 def getElementsByTagName(self, name):
Fred Drakefbe7b4f2001-07-04 06:25:53 +0000930 return _getElementsByTagNameHelper(self, name, [])
931
932 def getElementsByTagNameNS(self, namespaceURI, localName):
933 return _getElementsByTagNameNSHelper(self, namespaceURI, localName, [])
Fred Drake55c38192000-06-29 19:39:57 +0000934
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000935 def writexml(self, writer, indent="", addindent="", newl=""):
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000936 writer.write('<?xml version="1.0" ?>\n')
Fred Drake55c38192000-06-29 19:39:57 +0000937 for node in self.childNodes:
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000938 node.writexml(writer, indent, addindent, newl)
Fred Drake55c38192000-06-29 19:39:57 +0000939
Fred Drake4ccf4a12000-11-21 22:02:22 +0000940def _get_StringIO():
Fred Drakef7cf40d2000-12-14 18:16:11 +0000941 # we can't use cStringIO since it doesn't support Unicode strings
942 from StringIO import StringIO
Fred Drake4ccf4a12000-11-21 22:02:22 +0000943 return StringIO()
944
Fred Drake1f549022000-09-24 05:21:58 +0000945def _doparse(func, args, kwargs):
946 events = apply(func, args, kwargs)
947 toktype, rootNode = events.getEvent()
948 events.expandNode(rootNode)
Martin v. Löwisb417be22001-02-06 01:16:06 +0000949 events.clear()
Fred Drake55c38192000-06-29 19:39:57 +0000950 return rootNode
951
Fred Drake1f549022000-09-24 05:21:58 +0000952def parse(*args, **kwargs):
Fred Drakef7cf40d2000-12-14 18:16:11 +0000953 """Parse a file into a DOM by filename or file object."""
Fred Drake4ccf4a12000-11-21 22:02:22 +0000954 from xml.dom import pulldom
Fred Drake1f549022000-09-24 05:21:58 +0000955 return _doparse(pulldom.parse, args, kwargs)
Fred Drake55c38192000-06-29 19:39:57 +0000956
Fred Drake1f549022000-09-24 05:21:58 +0000957def parseString(*args, **kwargs):
Fred Drakef7cf40d2000-12-14 18:16:11 +0000958 """Parse a file into a DOM from a string."""
Fred Drake4ccf4a12000-11-21 22:02:22 +0000959 from xml.dom import pulldom
Fred Drake1f549022000-09-24 05:21:58 +0000960 return _doparse(pulldom.parseString, args, kwargs)
Martin v. Löwis7edbd4f2001-02-22 14:05:50 +0000961
962def getDOMImplementation():
963 return Document.implementation