| 1 |
"""Simple implementation of the Level 1 DOM. |
| 2 |
|
| 3 |
Namespaces and other minor Level 2 features are also supported. |
| 4 |
|
| 5 |
parse("foo.xml") |
| 6 |
|
| 7 |
parseString("<foo><bar/></foo>") |
| 8 |
|
| 9 |
Todo: |
| 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 |
|
| 18 |
import io |
| 19 |
import xml.dom |
| 20 |
|
| 21 |
from xml.dom import EMPTY_NAMESPACE, EMPTY_PREFIX, XMLNS_NAMESPACE, domreg |
| 22 |
from xml.dom.minicompat import * |
| 23 |
from xml.dom.xmlbuilder import DOMImplementationLS, DocumentLS |
| 24 |
|
| 25 |
# 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 |
# |
| 30 |
_nodeTypes_with_children = (xml.dom.Node.ELEMENT_NODE, |
| 31 |
xml.dom.Node.ENTITY_REFERENCE_NODE) |
| 32 |
|
| 33 |
|
| 34 |
class Node(xml.dom.Node): |
| 35 |
namespaceURI = None # this is non-null only for elements and attributes |
| 36 |
parentNode = None |
| 37 |
ownerDocument = None |
| 38 |
nextSibling = None |
| 39 |
previousSibling = None |
| 40 |
|
| 41 |
prefix = EMPTY_PREFIX # non-null only for NS elements and attributes |
| 42 |
|
| 43 |
def __bool__(self): |
| 44 |
return True |
| 45 |
|
| 46 |
def toxml(self, encoding=None, standalone=None): |
| 47 |
return self.toprettyxml("", "", encoding, standalone) |
| 48 |
|
| 49 |
def toprettyxml(self, indent="\t", newl="\n", encoding=None, |
| 50 |
standalone=None): |
| 51 |
if encoding is None: |
| 52 |
writer = io.StringIO() |
| 53 |
else: |
| 54 |
writer = io.TextIOWrapper(io.BytesIO(), |
| 55 |
encoding=encoding, |
| 56 |
errors="xmlcharrefreplace", |
| 57 |
newline='\n') |
| 58 |
if self.nodeType == Node.DOCUMENT_NODE: |
| 59 |
# Can pass encoding only to document, to put it into XML header |
| 60 |
self.writexml(writer, "", indent, newl, encoding, standalone) |
| 61 |
else: |
| 62 |
self.writexml(writer, "", indent, newl) |
| 63 |
if encoding is None: |
| 64 |
return writer.getvalue() |
| 65 |
else: |
| 66 |
return writer.detach().getvalue() |
| 67 |
|
| 68 |
def hasChildNodes(self): |
| 69 |
return bool(self.childNodes) |
| 70 |
|
| 71 |
def _get_childNodes(self): |
| 72 |
return self.childNodes |
| 73 |
|
| 74 |
def _get_firstChild(self): |
| 75 |
if self.childNodes: |
| 76 |
return self.childNodes[0] |
| 77 |
|
| 78 |
def _get_lastChild(self): |
| 79 |
if self.childNodes: |
| 80 |
return self.childNodes[-1] |
| 81 |
|
| 82 |
def insertBefore(self, newChild, refChild): |
| 83 |
if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE: |
| 84 |
for c in tuple(newChild.childNodes): |
| 85 |
self.insertBefore(c, refChild) |
| 86 |
### The DOM does not clearly specify what to return in this case |
| 87 |
return newChild |
| 88 |
if newChild.nodeType not in self._child_node_types: |
| 89 |
raise xml.dom.HierarchyRequestErr( |
| 90 |
"%s cannot be child of %s" % (repr(newChild), repr(self))) |
| 91 |
if newChild.parentNode is not None: |
| 92 |
newChild.parentNode.removeChild(newChild) |
| 93 |
if refChild is None: |
| 94 |
self.appendChild(newChild) |
| 95 |
else: |
| 96 |
try: |
| 97 |
index = self.childNodes.index(refChild) |
| 98 |
except ValueError: |
| 99 |
raise xml.dom.NotFoundErr() |
| 100 |
if newChild.nodeType in _nodeTypes_with_children: |
| 101 |
_clear_id_cache(self) |
| 102 |
self.childNodes.insert(index, newChild) |
| 103 |
newChild.nextSibling = refChild |
| 104 |
refChild.previousSibling = newChild |
| 105 |
if index: |
| 106 |
node = self.childNodes[index-1] |
| 107 |
node.nextSibling = newChild |
| 108 |
newChild.previousSibling = node |
| 109 |
else: |
| 110 |
newChild.previousSibling = None |
| 111 |
newChild.parentNode = self |
| 112 |
return newChild |
| 113 |
|
| 114 |
def appendChild(self, node): |
| 115 |
if node.nodeType == self.DOCUMENT_FRAGMENT_NODE: |
| 116 |
for c in tuple(node.childNodes): |
| 117 |
self.appendChild(c) |
| 118 |
### The DOM does not clearly specify what to return in this case |
| 119 |
return node |
| 120 |
if node.nodeType not in self._child_node_types: |
| 121 |
raise xml.dom.HierarchyRequestErr( |
| 122 |
"%s cannot be child of %s" % (repr(node), repr(self))) |
| 123 |
elif node.nodeType in _nodeTypes_with_children: |
| 124 |
_clear_id_cache(self) |
| 125 |
if node.parentNode is not None: |
| 126 |
node.parentNode.removeChild(node) |
| 127 |
_append_child(self, node) |
| 128 |
node.nextSibling = None |
| 129 |
return node |
| 130 |
|
| 131 |
def replaceChild(self, newChild, oldChild): |
| 132 |
if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE: |
| 133 |
refChild = oldChild.nextSibling |
| 134 |
self.removeChild(oldChild) |
| 135 |
return self.insertBefore(newChild, refChild) |
| 136 |
if newChild.nodeType not in self._child_node_types: |
| 137 |
raise xml.dom.HierarchyRequestErr( |
| 138 |
"%s cannot be child of %s" % (repr(newChild), repr(self))) |
| 139 |
if newChild is oldChild: |
| 140 |
return |
| 141 |
if newChild.parentNode is not None: |
| 142 |
newChild.parentNode.removeChild(newChild) |
| 143 |
try: |
| 144 |
index = self.childNodes.index(oldChild) |
| 145 |
except ValueError: |
| 146 |
raise xml.dom.NotFoundErr() |
| 147 |
self.childNodes[index] = newChild |
| 148 |
newChild.parentNode = self |
| 149 |
oldChild.parentNode = None |
| 150 |
if (newChild.nodeType in _nodeTypes_with_children |
| 151 |
or oldChild.nodeType in _nodeTypes_with_children): |
| 152 |
_clear_id_cache(self) |
| 153 |
newChild.nextSibling = oldChild.nextSibling |
| 154 |
newChild.previousSibling = oldChild.previousSibling |
| 155 |
oldChild.nextSibling = None |
| 156 |
oldChild.previousSibling = None |
| 157 |
if newChild.previousSibling: |
| 158 |
newChild.previousSibling.nextSibling = newChild |
| 159 |
if newChild.nextSibling: |
| 160 |
newChild.nextSibling.previousSibling = newChild |
| 161 |
return oldChild |
| 162 |
|
| 163 |
def removeChild(self, oldChild): |
| 164 |
try: |
| 165 |
self.childNodes.remove(oldChild) |
| 166 |
except ValueError: |
| 167 |
raise xml.dom.NotFoundErr() |
| 168 |
if oldChild.nextSibling is not None: |
| 169 |
oldChild.nextSibling.previousSibling = oldChild.previousSibling |
| 170 |
if oldChild.previousSibling is not None: |
| 171 |
oldChild.previousSibling.nextSibling = oldChild.nextSibling |
| 172 |
oldChild.nextSibling = oldChild.previousSibling = None |
| 173 |
if oldChild.nodeType in _nodeTypes_with_children: |
| 174 |
_clear_id_cache(self) |
| 175 |
|
| 176 |
oldChild.parentNode = None |
| 177 |
return oldChild |
| 178 |
|
| 179 |
def normalize(self): |
| 180 |
L = [] |
| 181 |
for child in self.childNodes: |
| 182 |
if child.nodeType == Node.TEXT_NODE: |
| 183 |
if not child.data: |
| 184 |
# empty text node; discard |
| 185 |
if L: |
| 186 |
L[-1].nextSibling = child.nextSibling |
| 187 |
if child.nextSibling: |
| 188 |
child.nextSibling.previousSibling = child.previousSibling |
| 189 |
child.unlink() |
| 190 |
elif L and L[-1].nodeType == child.nodeType: |
| 191 |
# collapse text node |
| 192 |
node = L[-1] |
| 193 |
node.data = node.data + child.data |
| 194 |
node.nextSibling = child.nextSibling |
| 195 |
if child.nextSibling: |
| 196 |
child.nextSibling.previousSibling = node |
| 197 |
child.unlink() |
| 198 |
else: |
| 199 |
L.append(child) |
| 200 |
else: |
| 201 |
L.append(child) |
| 202 |
if child.nodeType == Node.ELEMENT_NODE: |
| 203 |
child.normalize() |
| 204 |
self.childNodes[:] = L |
| 205 |
|
| 206 |
def cloneNode(self, deep): |
| 207 |
return _clone_node(self, deep, self.ownerDocument or self) |
| 208 |
|
| 209 |
def isSupported(self, feature, version): |
| 210 |
return self.ownerDocument.implementation.hasFeature(feature, version) |
| 211 |
|
| 212 |
def _get_localName(self): |
| 213 |
# Overridden in Element and Attr where localName can be Non-Null |
| 214 |
return None |
| 215 |
|
| 216 |
# Node interfaces from Level 3 (WD 9 April 2002) |
| 217 |
|
| 218 |
def isSameNode(self, other): |
| 219 |
return self is other |
| 220 |
|
| 221 |
def getInterface(self, feature): |
| 222 |
if self.isSupported(feature, None): |
| 223 |
return self |
| 224 |
else: |
| 225 |
return None |
| 226 |
|
| 227 |
# The "user data" functions use a dictionary that is only present |
| 228 |
# if some user data has been set, so be careful not to assume it |
| 229 |
# exists. |
| 230 |
|
| 231 |
def getUserData(self, key): |
| 232 |
try: |
| 233 |
return self._user_data[key][0] |
| 234 |
except (AttributeError, KeyError): |
| 235 |
return None |
| 236 |
|
| 237 |
def setUserData(self, key, data, handler): |
| 238 |
old = None |
| 239 |
try: |
| 240 |
d = self._user_data |
| 241 |
except AttributeError: |
| 242 |
d = {} |
| 243 |
self._user_data = d |
| 244 |
if key in d: |
| 245 |
old = d[key][0] |
| 246 |
if data is None: |
| 247 |
# ignore handlers passed for None |
| 248 |
handler = None |
| 249 |
if old is not None: |
| 250 |
del d[key] |
| 251 |
else: |
| 252 |
d[key] = (data, handler) |
| 253 |
return old |
| 254 |
|
| 255 |
def _call_user_data_handler(self, operation, src, dst): |
| 256 |
if hasattr(self, "_user_data"): |
| 257 |
for key, (data, handler) in list(self._user_data.items()): |
| 258 |
if handler is not None: |
| 259 |
handler.handle(operation, key, data, src, dst) |
| 260 |
|
| 261 |
# minidom-specific API: |
| 262 |
|
| 263 |
def unlink(self): |
| 264 |
self.parentNode = self.ownerDocument = None |
| 265 |
if self.childNodes: |
| 266 |
for child in self.childNodes: |
| 267 |
child.unlink() |
| 268 |
self.childNodes = NodeList() |
| 269 |
self.previousSibling = None |
| 270 |
self.nextSibling = None |
| 271 |
|
| 272 |
# A Node is its own context manager, to ensure that an unlink() call occurs. |
| 273 |
# This is similar to how a file object works. |
| 274 |
def __enter__(self): |
| 275 |
return self |
| 276 |
|
| 277 |
def __exit__(self, et, ev, tb): |
| 278 |
self.unlink() |
| 279 |
|
| 280 |
defproperty(Node, "firstChild", doc="First child node, or None.") |
| 281 |
defproperty(Node, "lastChild", doc="Last child node, or None.") |
| 282 |
defproperty(Node, "localName", doc="Namespace-local name of this node.") |
| 283 |
|
| 284 |
|
| 285 |
def _append_child(self, node): |
| 286 |
# fast path with less checks; usable by DOM builders if careful |
| 287 |
childNodes = self.childNodes |
| 288 |
if childNodes: |
| 289 |
last = childNodes[-1] |
| 290 |
node.previousSibling = last |
| 291 |
last.nextSibling = node |
| 292 |
childNodes.append(node) |
| 293 |
node.parentNode = self |
| 294 |
|
| 295 |
|
| 296 |
def _write_data(writer, text, attr): |
| 297 |
"Writes datachars to writer." |
| 298 |
if not text: |
| 299 |
return |
| 300 |
# See the comments in ElementTree.py for behavior and |
| 301 |
# implementation details. |
| 302 |
if "&" in text: |
| 303 |
text = text.replace("&", "&") |
| 304 |
if "<" in text: |
| 305 |
text = text.replace("<", "<") |
| 306 |
if ">" in text: |
| 307 |
text = text.replace(">", ">") |
| 308 |
if attr: |
| 309 |
if '"' in text: |
| 310 |
text = text.replace('"', """) |
| 311 |
if "\r" in text: |
| 312 |
text = text.replace("\r", " ") |
| 313 |
if "\n" in text: |
| 314 |
text = text.replace("\n", " ") |
| 315 |
if "\t" in text: |
| 316 |
text = text.replace("\t", "	") |
| 317 |
writer.write(text) |
| 318 |
|
| 319 |
def _get_elements_by_tagName_helper(parent, name, rc): |
| 320 |
for node in parent.childNodes: |
| 321 |
if node.nodeType == Node.ELEMENT_NODE and \ |
| 322 |
(name == "*" or node.tagName == name): |
| 323 |
rc.append(node) |
| 324 |
_get_elements_by_tagName_helper(node, name, rc) |
| 325 |
return rc |
| 326 |
|
| 327 |
def _get_elements_by_tagName_ns_helper(parent, nsURI, localName, rc): |
| 328 |
for node in parent.childNodes: |
| 329 |
if node.nodeType == Node.ELEMENT_NODE: |
| 330 |
if ((localName == "*" or node.localName == localName) and |
| 331 |
(nsURI == "*" or node.namespaceURI == nsURI)): |
| 332 |
rc.append(node) |
| 333 |
_get_elements_by_tagName_ns_helper(node, nsURI, localName, rc) |
| 334 |
return rc |
| 335 |
|
| 336 |
class DocumentFragment(Node): |
| 337 |
nodeType = Node.DOCUMENT_FRAGMENT_NODE |
| 338 |
nodeName = "#document-fragment" |
| 339 |
nodeValue = None |
| 340 |
attributes = None |
| 341 |
parentNode = None |
| 342 |
_child_node_types = (Node.ELEMENT_NODE, |
| 343 |
Node.TEXT_NODE, |
| 344 |
Node.CDATA_SECTION_NODE, |
| 345 |
Node.ENTITY_REFERENCE_NODE, |
| 346 |
Node.PROCESSING_INSTRUCTION_NODE, |
| 347 |
Node.COMMENT_NODE, |
| 348 |
Node.NOTATION_NODE) |
| 349 |
|
| 350 |
def __init__(self): |
| 351 |
self.childNodes = NodeList() |
| 352 |
|
| 353 |
|
| 354 |
class Attr(Node): |
| 355 |
__slots__=('_name', '_value', 'namespaceURI', |
| 356 |
'_prefix', 'childNodes', '_localName', 'ownerDocument', 'ownerElement') |
| 357 |
nodeType = Node.ATTRIBUTE_NODE |
| 358 |
attributes = None |
| 359 |
specified = False |
| 360 |
_is_id = False |
| 361 |
|
| 362 |
_child_node_types = (Node.TEXT_NODE, Node.ENTITY_REFERENCE_NODE) |
| 363 |
|
| 364 |
def __init__(self, qName, namespaceURI=EMPTY_NAMESPACE, localName=None, |
| 365 |
prefix=None): |
| 366 |
self.ownerElement = None |
| 367 |
self.ownerDocument = None |
| 368 |
self._name = qName |
| 369 |
self.namespaceURI = namespaceURI |
| 370 |
self._prefix = prefix |
| 371 |
if localName is not None: |
| 372 |
self._localName = localName |
| 373 |
self.childNodes = NodeList() |
| 374 |
|
| 375 |
# Add the single child node that represents the value of the attr |
| 376 |
self.childNodes.append(Text()) |
| 377 |
|
| 378 |
# nodeValue and value are set elsewhere |
| 379 |
|
| 380 |
def _get_localName(self): |
| 381 |
try: |
| 382 |
return self._localName |
| 383 |
except AttributeError: |
| 384 |
return self.nodeName.split(":", 1)[-1] |
| 385 |
|
| 386 |
def _get_specified(self): |
| 387 |
return self.specified |
| 388 |
|
| 389 |
def _get_name(self): |
| 390 |
return self._name |
| 391 |
|
| 392 |
def _set_name(self, value): |
| 393 |
self._name = value |
| 394 |
if self.ownerElement is not None: |
| 395 |
_clear_id_cache(self.ownerElement) |
| 396 |
|
| 397 |
nodeName = name = property(_get_name, _set_name) |
| 398 |
|
| 399 |
def _get_value(self): |
| 400 |
return self._value |
| 401 |
|
| 402 |
def _set_value(self, value): |
| 403 |
self._value = value |
| 404 |
self.childNodes[0].data = value |
| 405 |
if self.ownerElement is not None: |
| 406 |
_clear_id_cache(self.ownerElement) |
| 407 |
self.childNodes[0].data = value |
| 408 |
|
| 409 |
nodeValue = value = property(_get_value, _set_value) |
| 410 |
|
| 411 |
def _get_prefix(self): |
| 412 |
return self._prefix |
| 413 |
|
| 414 |
def _set_prefix(self, prefix): |
| 415 |
nsuri = self.namespaceURI |
| 416 |
if prefix == "xmlns": |
| 417 |
if nsuri and nsuri != XMLNS_NAMESPACE: |
| 418 |
raise xml.dom.NamespaceErr( |
| 419 |
"illegal use of 'xmlns' prefix for the wrong namespace") |
| 420 |
self._prefix = prefix |
| 421 |
if prefix is None: |
| 422 |
newName = self.localName |
| 423 |
else: |
| 424 |
newName = "%s:%s" % (prefix, self.localName) |
| 425 |
if self.ownerElement: |
| 426 |
_clear_id_cache(self.ownerElement) |
| 427 |
self.name = newName |
| 428 |
|
| 429 |
prefix = property(_get_prefix, _set_prefix) |
| 430 |
|
| 431 |
def unlink(self): |
| 432 |
# This implementation does not call the base implementation |
| 433 |
# since most of that is not needed, and the expense of the |
| 434 |
# method call is not warranted. We duplicate the removal of |
| 435 |
# children, but that's all we needed from the base class. |
| 436 |
elem = self.ownerElement |
| 437 |
if elem is not None: |
| 438 |
del elem._attrs[self.nodeName] |
| 439 |
del elem._attrsNS[(self.namespaceURI, self.localName)] |
| 440 |
if self._is_id: |
| 441 |
self._is_id = False |
| 442 |
elem._magic_id_nodes -= 1 |
| 443 |
self.ownerDocument._magic_id_count -= 1 |
| 444 |
for child in self.childNodes: |
| 445 |
child.unlink() |
| 446 |
del self.childNodes[:] |
| 447 |
|
| 448 |
def _get_isId(self): |
| 449 |
if self._is_id: |
| 450 |
return True |
| 451 |
doc = self.ownerDocument |
| 452 |
elem = self.ownerElement |
| 453 |
if doc is None or elem is None: |
| 454 |
return False |
| 455 |
|
| 456 |
info = doc._get_elem_info(elem) |
| 457 |
if info is None: |
| 458 |
return False |
| 459 |
if self.namespaceURI: |
| 460 |
return info.isIdNS(self.namespaceURI, self.localName) |
| 461 |
else: |
| 462 |
return info.isId(self.nodeName) |
| 463 |
|
| 464 |
def _get_schemaType(self): |
| 465 |
doc = self.ownerDocument |
| 466 |
elem = self.ownerElement |
| 467 |
if doc is None or elem is None: |
| 468 |
return _no_type |
| 469 |
|
| 470 |
info = doc._get_elem_info(elem) |
| 471 |
if info is None: |
| 472 |
return _no_type |
| 473 |
if self.namespaceURI: |
| 474 |
return info.getAttributeTypeNS(self.namespaceURI, self.localName) |
| 475 |
else: |
| 476 |
return info.getAttributeType(self.nodeName) |
| 477 |
|
| 478 |
defproperty(Attr, "isId", doc="True if this attribute is an ID.") |
| 479 |
defproperty(Attr, "localName", doc="Namespace-local name of this attribute.") |
| 480 |
defproperty(Attr, "schemaType", doc="Schema type for this attribute.") |
| 481 |
|
| 482 |
|
| 483 |
class NamedNodeMap(object): |
| 484 |
"""The attribute list is a transient interface to the underlying |
| 485 |
dictionaries. Mutations here will change the underlying element's |
| 486 |
dictionary. |
| 487 |
|
| 488 |
Ordering is imposed artificially and does not reflect the order of |
| 489 |
attributes as found in an input document. |
| 490 |
""" |
| 491 |
|
| 492 |
__slots__ = ('_attrs', '_attrsNS', '_ownerElement') |
| 493 |
|
| 494 |
def __init__(self, attrs, attrsNS, ownerElement): |
| 495 |
self._attrs = attrs |
| 496 |
self._attrsNS = attrsNS |
| 497 |
self._ownerElement = ownerElement |
| 498 |
|
| 499 |
def _get_length(self): |
| 500 |
return len(self._attrs) |
| 501 |
|
| 502 |
def item(self, index): |
| 503 |
try: |
| 504 |
return self[list(self._attrs.keys())[index]] |
| 505 |
except IndexError: |
| 506 |
return None |
| 507 |
|
| 508 |
def items(self): |
| 509 |
L = [] |
| 510 |
for node in self._attrs.values(): |
| 511 |
L.append((node.nodeName, node.value)) |
| 512 |
return L |
| 513 |
|
| 514 |
def itemsNS(self): |
| 515 |
L = [] |
| 516 |
for node in self._attrs.values(): |
| 517 |
L.append(((node.namespaceURI, node.localName), node.value)) |
| 518 |
return L |
| 519 |
|
| 520 |
def __contains__(self, key): |
| 521 |
if isinstance(key, str): |
| 522 |
return key in self._attrs |
| 523 |
else: |
| 524 |
return key in self._attrsNS |
| 525 |
|
| 526 |
def keys(self): |
| 527 |
return self._attrs.keys() |
| 528 |
|
| 529 |
def keysNS(self): |
| 530 |
return self._attrsNS.keys() |
| 531 |
|
| 532 |
def values(self): |
| 533 |
return self._attrs.values() |
| 534 |
|
| 535 |
def get(self, name, value=None): |
| 536 |
return self._attrs.get(name, value) |
| 537 |
|
| 538 |
__len__ = _get_length |
| 539 |
|
| 540 |
def _cmp(self, other): |
| 541 |
if self._attrs is getattr(other, "_attrs", None): |
| 542 |
return 0 |
| 543 |
else: |
| 544 |
return (id(self) > id(other)) - (id(self) < id(other)) |
| 545 |
|
| 546 |
def __eq__(self, other): |
| 547 |
return self._cmp(other) == 0 |
| 548 |
|
| 549 |
def __ge__(self, other): |
| 550 |
return self._cmp(other) >= 0 |
| 551 |
|
| 552 |
def __gt__(self, other): |
| 553 |
return self._cmp(other) > 0 |
| 554 |
|
| 555 |
def __le__(self, other): |
| 556 |
return self._cmp(other) <= 0 |
| 557 |
|
| 558 |
def __lt__(self, other): |
| 559 |
return self._cmp(other) < 0 |
| 560 |
|
| 561 |
def __getitem__(self, attname_or_tuple): |
| 562 |
if isinstance(attname_or_tuple, tuple): |
| 563 |
return self._attrsNS[attname_or_tuple] |
| 564 |
else: |
| 565 |
return self._attrs[attname_or_tuple] |
| 566 |
|
| 567 |
# same as set |
| 568 |
def __setitem__(self, attname, value): |
| 569 |
if isinstance(value, str): |
| 570 |
try: |
| 571 |
node = self._attrs[attname] |
| 572 |
except KeyError: |
| 573 |
node = Attr(attname) |
| 574 |
node.ownerDocument = self._ownerElement.ownerDocument |
| 575 |
self.setNamedItem(node) |
| 576 |
node.value = value |
| 577 |
else: |
| 578 |
if not isinstance(value, Attr): |
| 579 |
raise TypeError("value must be a string or Attr object") |
| 580 |
node = value |
| 581 |
self.setNamedItem(node) |
| 582 |
|
| 583 |
def getNamedItem(self, name): |
| 584 |
try: |
| 585 |
return self._attrs[name] |
| 586 |
except KeyError: |
| 587 |
return None |
| 588 |
|
| 589 |
def getNamedItemNS(self, namespaceURI, localName): |
| 590 |
try: |
| 591 |
return self._attrsNS[(namespaceURI, localName)] |
| 592 |
except KeyError: |
| 593 |
return None |
| 594 |
|
| 595 |
def removeNamedItem(self, name): |
| 596 |
n = self.getNamedItem(name) |
| 597 |
if n is not None: |
| 598 |
_clear_id_cache(self._ownerElement) |
| 599 |
del self._attrs[n.nodeName] |
| 600 |
del self._attrsNS[(n.namespaceURI, n.localName)] |
| 601 |
if hasattr(n, 'ownerElement'): |
| 602 |
n.ownerElement = None |
| 603 |
return n |
| 604 |
else: |
| 605 |
raise xml.dom.NotFoundErr() |
| 606 |
|
| 607 |
def removeNamedItemNS(self, namespaceURI, localName): |
| 608 |
n = self.getNamedItemNS(namespaceURI, localName) |
| 609 |
if n is not None: |
| 610 |
_clear_id_cache(self._ownerElement) |
| 611 |
del self._attrsNS[(n.namespaceURI, n.localName)] |
| 612 |
del self._attrs[n.nodeName] |
| 613 |
if hasattr(n, 'ownerElement'): |
| 614 |
n.ownerElement = None |
| 615 |
return n |
| 616 |
else: |
| 617 |
raise xml.dom.NotFoundErr() |
| 618 |
|
| 619 |
def setNamedItem(self, node): |
| 620 |
if not isinstance(node, Attr): |
| 621 |
raise xml.dom.HierarchyRequestErr( |
| 622 |
"%s cannot be child of %s" % (repr(node), repr(self))) |
| 623 |
old = self._attrs.get(node.name) |
| 624 |
if old: |
| 625 |
old.unlink() |
| 626 |
self._attrs[node.name] = node |
| 627 |
self._attrsNS[(node.namespaceURI, node.localName)] = node |
| 628 |
node.ownerElement = self._ownerElement |
| 629 |
_clear_id_cache(node.ownerElement) |
| 630 |
return old |
| 631 |
|
| 632 |
def setNamedItemNS(self, node): |
| 633 |
return self.setNamedItem(node) |
| 634 |
|
| 635 |
def __delitem__(self, attname_or_tuple): |
| 636 |
node = self[attname_or_tuple] |
| 637 |
_clear_id_cache(node.ownerElement) |
| 638 |
node.unlink() |
| 639 |
|
| 640 |
def __getstate__(self): |
| 641 |
return self._attrs, self._attrsNS, self._ownerElement |
| 642 |
|
| 643 |
def __setstate__(self, state): |
| 644 |
self._attrs, self._attrsNS, self._ownerElement = state |
| 645 |
|
| 646 |
defproperty(NamedNodeMap, "length", |
| 647 |
doc="Number of nodes in the NamedNodeMap.") |
| 648 |
|
| 649 |
AttributeList = NamedNodeMap |
| 650 |
|
| 651 |
|
| 652 |
class TypeInfo(object): |
| 653 |
__slots__ = 'namespace', 'name' |
| 654 |
|
| 655 |
def __init__(self, namespace, name): |
| 656 |
self.namespace = namespace |
| 657 |
self.name = name |
| 658 |
|
| 659 |
def __repr__(self): |
| 660 |
if self.namespace: |
| 661 |
return "<%s %r (from %r)>" % (self.__class__.__name__, self.name, |
| 662 |
self.namespace) |
| 663 |
else: |
| 664 |
return "<%s %r>" % (self.__class__.__name__, self.name) |
| 665 |
|
| 666 |
def _get_name(self): |
| 667 |
return self.name |
| 668 |
|
| 669 |
def _get_namespace(self): |
| 670 |
return self.namespace |
| 671 |
|
| 672 |
_no_type = TypeInfo(None, None) |
| 673 |
|
| 674 |
class Element(Node): |
| 675 |
__slots__=('ownerDocument', 'parentNode', 'tagName', 'nodeName', 'prefix', |
| 676 |
'namespaceURI', '_localName', 'childNodes', '_attrs', '_attrsNS', |
| 677 |
'nextSibling', 'previousSibling') |
| 678 |
nodeType = Node.ELEMENT_NODE |
| 679 |
nodeValue = None |
| 680 |
schemaType = _no_type |
| 681 |
|
| 682 |
_magic_id_nodes = 0 |
| 683 |
|
| 684 |
_child_node_types = (Node.ELEMENT_NODE, |
| 685 |
Node.PROCESSING_INSTRUCTION_NODE, |
| 686 |
Node.COMMENT_NODE, |
| 687 |
Node.TEXT_NODE, |
| 688 |
Node.CDATA_SECTION_NODE, |
| 689 |
Node.ENTITY_REFERENCE_NODE) |
| 690 |
|
| 691 |
def __init__(self, tagName, namespaceURI=EMPTY_NAMESPACE, prefix=None, |
| 692 |
localName=None): |
| 693 |
self.ownerDocument = None |
| 694 |
self.parentNode = None |
| 695 |
self.tagName = self.nodeName = tagName |
| 696 |
self.prefix = prefix |
| 697 |
self.namespaceURI = namespaceURI |
| 698 |
self.childNodes = NodeList() |
| 699 |
self.nextSibling = self.previousSibling = None |
| 700 |
|
| 701 |
# Attribute dictionaries are lazily created |
| 702 |
# attributes are double-indexed: |
| 703 |
# tagName -> Attribute |
| 704 |
# URI,localName -> Attribute |
| 705 |
# in the future: consider lazy generation |
| 706 |
# of attribute objects this is too tricky |
| 707 |
# for now because of headaches with |
| 708 |
# namespaces. |
| 709 |
self._attrs = None |
| 710 |
self._attrsNS = None |
| 711 |
|
| 712 |
def _ensure_attributes(self): |
| 713 |
if self._attrs is None: |
| 714 |
self._attrs = {} |
| 715 |
self._attrsNS = {} |
| 716 |
|
| 717 |
def _get_localName(self): |
| 718 |
try: |
| 719 |
return self._localName |
| 720 |
except AttributeError: |
| 721 |
return self.tagName.split(":", 1)[-1] |
| 722 |
|
| 723 |
def _get_tagName(self): |
| 724 |
return self.tagName |
| 725 |
|
| 726 |
def unlink(self): |
| 727 |
if self._attrs is not None: |
| 728 |
for attr in list(self._attrs.values()): |
| 729 |
attr.unlink() |
| 730 |
self._attrs = None |
| 731 |
self._attrsNS = None |
| 732 |
Node.unlink(self) |
| 733 |
|
| 734 |
def getAttribute(self, attname): |
| 735 |
"""Returns the value of the specified attribute. |
| 736 |
|
| 737 |
Returns the value of the element's attribute named attname as |
| 738 |
a string. An empty string is returned if the element does not |
| 739 |
have such an attribute. Note that an empty string may also be |
| 740 |
returned as an explicitly given attribute value, use the |
| 741 |
hasAttribute method to distinguish these two cases. |
| 742 |
""" |
| 743 |
if self._attrs is None: |
| 744 |
return "" |
| 745 |
try: |
| 746 |
return self._attrs[attname].value |
| 747 |
except KeyError: |
| 748 |
return "" |
| 749 |
|
| 750 |
def getAttributeNS(self, namespaceURI, localName): |
| 751 |
if self._attrsNS is None: |
| 752 |
return "" |
| 753 |
try: |
| 754 |
return self._attrsNS[(namespaceURI, localName)].value |
| 755 |
except KeyError: |
| 756 |
return "" |
| 757 |
|
| 758 |
def setAttribute(self, attname, value): |
| 759 |
attr = self.getAttributeNode(attname) |
| 760 |
if attr is None: |
| 761 |
attr = Attr(attname) |
| 762 |
attr.value = value # also sets nodeValue |
| 763 |
attr.ownerDocument = self.ownerDocument |
| 764 |
self.setAttributeNode(attr) |
| 765 |
elif value != attr.value: |
| 766 |
attr.value = value |
| 767 |
if attr.isId: |
| 768 |
_clear_id_cache(self) |
| 769 |
|
| 770 |
def setAttributeNS(self, namespaceURI, qualifiedName, value): |
| 771 |
prefix, localname = _nssplit(qualifiedName) |
| 772 |
attr = self.getAttributeNodeNS(namespaceURI, localname) |
| 773 |
if attr is None: |
| 774 |
attr = Attr(qualifiedName, namespaceURI, localname, prefix) |
| 775 |
attr.value = value |
| 776 |
attr.ownerDocument = self.ownerDocument |
| 777 |
self.setAttributeNode(attr) |
| 778 |
else: |
| 779 |
if value != attr.value: |
| 780 |
attr.value = value |
| 781 |
if attr.isId: |
| 782 |
_clear_id_cache(self) |
| 783 |
if attr.prefix != prefix: |
| 784 |
attr.prefix = prefix |
| 785 |
attr.nodeName = qualifiedName |
| 786 |
|
| 787 |
def getAttributeNode(self, attrname): |
| 788 |
if self._attrs is None: |
| 789 |
return None |
| 790 |
return self._attrs.get(attrname) |
| 791 |
|
| 792 |
def getAttributeNodeNS(self, namespaceURI, localName): |
| 793 |
if self._attrsNS is None: |
| 794 |
return None |
| 795 |
return self._attrsNS.get((namespaceURI, localName)) |
| 796 |
|
| 797 |
def setAttributeNode(self, attr): |
| 798 |
if attr.ownerElement not in (None, self): |
| 799 |
raise xml.dom.InuseAttributeErr("attribute node already owned") |
| 800 |
self._ensure_attributes() |
| 801 |
old1 = self._attrs.get(attr.name, None) |
| 802 |
if old1 is not None: |
| 803 |
self.removeAttributeNode(old1) |
| 804 |
old2 = self._attrsNS.get((attr.namespaceURI, attr.localName), None) |
| 805 |
if old2 is not None and old2 is not old1: |
| 806 |
self.removeAttributeNode(old2) |
| 807 |
_set_attribute_node(self, attr) |
| 808 |
|
| 809 |
if old1 is not attr: |
| 810 |
# It might have already been part of this node, in which case |
| 811 |
# it doesn't represent a change, and should not be returned. |
| 812 |
return old1 |
| 813 |
if old2 is not attr: |
| 814 |
return old2 |
| 815 |
|
| 816 |
setAttributeNodeNS = setAttributeNode |
| 817 |
|
| 818 |
def removeAttribute(self, name): |
| 819 |
if self._attrsNS is None: |
| 820 |
raise xml.dom.NotFoundErr() |
| 821 |
try: |
| 822 |
attr = self._attrs[name] |
| 823 |
except KeyError: |
| 824 |
raise xml.dom.NotFoundErr() |
| 825 |
self.removeAttributeNode(attr) |
| 826 |
|
| 827 |
def removeAttributeNS(self, namespaceURI, localName): |
| 828 |
if self._attrsNS is None: |
| 829 |
raise xml.dom.NotFoundErr() |
| 830 |
try: |
| 831 |
attr = self._attrsNS[(namespaceURI, localName)] |
| 832 |
except KeyError: |
| 833 |
raise xml.dom.NotFoundErr() |
| 834 |
self.removeAttributeNode(attr) |
| 835 |
|
| 836 |
def removeAttributeNode(self, node): |
| 837 |
if node is None: |
| 838 |
raise xml.dom.NotFoundErr() |
| 839 |
try: |
| 840 |
self._attrs[node.name] |
| 841 |
except KeyError: |
| 842 |
raise xml.dom.NotFoundErr() |
| 843 |
_clear_id_cache(self) |
| 844 |
node.unlink() |
| 845 |
# Restore this since the node is still useful and otherwise |
| 846 |
# unlinked |
| 847 |
node.ownerDocument = self.ownerDocument |
| 848 |
return node |
| 849 |
|
| 850 |
removeAttributeNodeNS = removeAttributeNode |
| 851 |
|
| 852 |
def hasAttribute(self, name): |
| 853 |
"""Checks whether the element has an attribute with the specified name. |
| 854 |
|
| 855 |
Returns True if the element has an attribute with the specified name. |
| 856 |
Otherwise, returns False. |
| 857 |
""" |
| 858 |
if self._attrs is None: |
| 859 |
return False |
| 860 |
return name in self._attrs |
| 861 |
|
| 862 |
def hasAttributeNS(self, namespaceURI, localName): |
| 863 |
if self._attrsNS is None: |
| 864 |
return False |
| 865 |
return (namespaceURI, localName) in self._attrsNS |
| 866 |
|
| 867 |
def getElementsByTagName(self, name): |
| 868 |
"""Returns all descendant elements with the given tag name. |
| 869 |
|
| 870 |
Returns the list of all descendant elements (not direct children |
| 871 |
only) with the specified tag name. |
| 872 |
""" |
| 873 |
return _get_elements_by_tagName_helper(self, name, NodeList()) |
| 874 |
|
| 875 |
def getElementsByTagNameNS(self, namespaceURI, localName): |
| 876 |
return _get_elements_by_tagName_ns_helper( |
| 877 |
self, namespaceURI, localName, NodeList()) |
| 878 |
|
| 879 |
def __repr__(self): |
| 880 |
return "<DOM Element: %s at %#x>" % (self.tagName, id(self)) |
| 881 |
|
| 882 |
def writexml(self, writer, indent="", addindent="", newl=""): |
| 883 |
"""Write an XML element to a file-like object |
| 884 |
|
| 885 |
Write the element to the writer object that must provide |
| 886 |
a write method (e.g. a file or StringIO object). |
| 887 |
""" |
| 888 |
# indent = current indentation |
| 889 |
# addindent = indentation to add to higher levels |
| 890 |
# newl = newline string |
| 891 |
writer.write(indent+"<" + self.tagName) |
| 892 |
|
| 893 |
attrs = self._get_attributes() |
| 894 |
|
| 895 |
for a_name in attrs.keys(): |
| 896 |
writer.write(" %s=\"" % a_name) |
| 897 |
_write_data(writer, attrs[a_name].value, True) |
| 898 |
writer.write("\"") |
| 899 |
if self.childNodes: |
| 900 |
writer.write(">") |
| 901 |
if (len(self.childNodes) == 1 and |
| 902 |
self.childNodes[0].nodeType in ( |
| 903 |
Node.TEXT_NODE, Node.CDATA_SECTION_NODE)): |
| 904 |
self.childNodes[0].writexml(writer, '', '', '') |
| 905 |
else: |
| 906 |
writer.write(newl) |
| 907 |
for node in self.childNodes: |
| 908 |
node.writexml(writer, indent+addindent, addindent, newl) |
| 909 |
writer.write(indent) |
| 910 |
writer.write("</%s>%s" % (self.tagName, newl)) |
| 911 |
else: |
| 912 |
writer.write("/>%s"%(newl)) |
| 913 |
|
| 914 |
def _get_attributes(self): |
| 915 |
self._ensure_attributes() |
| 916 |
return NamedNodeMap(self._attrs, self._attrsNS, self) |
| 917 |
|
| 918 |
def hasAttributes(self): |
| 919 |
if self._attrs: |
| 920 |
return True |
| 921 |
else: |
| 922 |
return False |
| 923 |
|
| 924 |
# DOM Level 3 attributes, based on the 22 Oct 2002 draft |
| 925 |
|
| 926 |
def setIdAttribute(self, name): |
| 927 |
idAttr = self.getAttributeNode(name) |
| 928 |
self.setIdAttributeNode(idAttr) |
| 929 |
|
| 930 |
def setIdAttributeNS(self, namespaceURI, localName): |
| 931 |
idAttr = self.getAttributeNodeNS(namespaceURI, localName) |
| 932 |
self.setIdAttributeNode(idAttr) |
| 933 |
|
| 934 |
def setIdAttributeNode(self, idAttr): |
| 935 |
if idAttr is None or not self.isSameNode(idAttr.ownerElement): |
| 936 |
raise xml.dom.NotFoundErr() |
| 937 |
if _get_containing_entref(self) is not None: |
| 938 |
raise xml.dom.NoModificationAllowedErr() |
| 939 |
if not idAttr._is_id: |
| 940 |
idAttr._is_id = True |
| 941 |
self._magic_id_nodes += 1 |
| 942 |
self.ownerDocument._magic_id_count += 1 |
| 943 |
_clear_id_cache(self) |
| 944 |
|
| 945 |
defproperty(Element, "attributes", |
| 946 |
doc="NamedNodeMap of attributes on the element.") |
| 947 |
defproperty(Element, "localName", |
| 948 |
doc="Namespace-local name of this element.") |
| 949 |
|
| 950 |
|
| 951 |
def _set_attribute_node(element, attr): |
| 952 |
_clear_id_cache(element) |
| 953 |
element._ensure_attributes() |
| 954 |
element._attrs[attr.name] = attr |
| 955 |
element._attrsNS[(attr.namespaceURI, attr.localName)] = attr |
| 956 |
|
| 957 |
# This creates a circular reference, but Element.unlink() |
| 958 |
# breaks the cycle since the references to the attribute |
| 959 |
# dictionaries are tossed. |
| 960 |
attr.ownerElement = element |
| 961 |
|
| 962 |
class Childless: |
| 963 |
"""Mixin that makes childless-ness easy to implement and avoids |
| 964 |
the complexity of the Node methods that deal with children. |
| 965 |
""" |
| 966 |
__slots__ = () |
| 967 |
|
| 968 |
attributes = None |
| 969 |
childNodes = EmptyNodeList() |
| 970 |
firstChild = None |
| 971 |
lastChild = None |
| 972 |
|
| 973 |
def _get_firstChild(self): |
| 974 |
return None |
| 975 |
|
| 976 |
def _get_lastChild(self): |
| 977 |
return None |
| 978 |
|
| 979 |
def appendChild(self, node): |
| 980 |
raise xml.dom.HierarchyRequestErr( |
| 981 |
self.nodeName + " nodes cannot have children") |
| 982 |
|
| 983 |
def hasChildNodes(self): |
| 984 |
return False |
| 985 |
|
| 986 |
def insertBefore(self, newChild, refChild): |
| 987 |
raise xml.dom.HierarchyRequestErr( |
| 988 |
self.nodeName + " nodes do not have children") |
| 989 |
|
| 990 |
def removeChild(self, oldChild): |
| 991 |
raise xml.dom.NotFoundErr( |
| 992 |
self.nodeName + " nodes do not have children") |
| 993 |
|
| 994 |
def normalize(self): |
| 995 |
# For childless nodes, normalize() has nothing to do. |
| 996 |
pass |
| 997 |
|
| 998 |
def replaceChild(self, newChild, oldChild): |
| 999 |
raise xml.dom.HierarchyRequestErr( |
| 1000 |
self.nodeName + " nodes do not have children") |
| 1001 |
|
| 1002 |
|
| 1003 |
class ProcessingInstruction(Childless, Node): |
| 1004 |
nodeType = Node.PROCESSING_INSTRUCTION_NODE |
| 1005 |
__slots__ = ('target', 'data') |
| 1006 |
|
| 1007 |
def __init__(self, target, data): |
| 1008 |
self.target = target |
| 1009 |
self.data = data |
| 1010 |
|
| 1011 |
# nodeValue is an alias for data |
| 1012 |
def _get_nodeValue(self): |
| 1013 |
return self.data |
| 1014 |
def _set_nodeValue(self, value): |
| 1015 |
self.data = value |
| 1016 |
nodeValue = property(_get_nodeValue, _set_nodeValue) |
| 1017 |
|
| 1018 |
# nodeName is an alias for target |
| 1019 |
def _get_nodeName(self): |
| 1020 |
return self.target |
| 1021 |
def _set_nodeName(self, value): |
| 1022 |
self.target = value |
| 1023 |
nodeName = property(_get_nodeName, _set_nodeName) |
| 1024 |
|
| 1025 |
def writexml(self, writer, indent="", addindent="", newl=""): |
| 1026 |
writer.write("%s<?%s %s?>%s" % (indent,self.target, self.data, newl)) |
| 1027 |
|
| 1028 |
|
| 1029 |
class CharacterData(Childless, Node): |
| 1030 |
__slots__=('_data', 'ownerDocument','parentNode', 'previousSibling', 'nextSibling') |
| 1031 |
|
| 1032 |
def __init__(self): |
| 1033 |
self.ownerDocument = self.parentNode = None |
| 1034 |
self.previousSibling = self.nextSibling = None |
| 1035 |
self._data = '' |
| 1036 |
Node.__init__(self) |
| 1037 |
|
| 1038 |
def _get_length(self): |
| 1039 |
return len(self.data) |
| 1040 |
__len__ = _get_length |
| 1041 |
|
| 1042 |
def _get_data(self): |
| 1043 |
return self._data |
| 1044 |
def _set_data(self, data): |
| 1045 |
self._data = data |
| 1046 |
|
| 1047 |
data = nodeValue = property(_get_data, _set_data) |
| 1048 |
|
| 1049 |
def __repr__(self): |
| 1050 |
data = self.data |
| 1051 |
if len(data) > 10: |
| 1052 |
dotdotdot = "..." |
| 1053 |
else: |
| 1054 |
dotdotdot = "" |
| 1055 |
return '<DOM %s node "%r%s">' % ( |
| 1056 |
self.__class__.__name__, data[0:10], dotdotdot) |
| 1057 |
|
| 1058 |
def substringData(self, offset, count): |
| 1059 |
if offset < 0: |
| 1060 |
raise xml.dom.IndexSizeErr("offset cannot be negative") |
| 1061 |
if offset >= len(self.data): |
| 1062 |
raise xml.dom.IndexSizeErr("offset cannot be beyond end of data") |
| 1063 |
if count < 0: |
| 1064 |
raise xml.dom.IndexSizeErr("count cannot be negative") |
| 1065 |
return self.data[offset:offset+count] |
| 1066 |
|
| 1067 |
def appendData(self, arg): |
| 1068 |
self.data = self.data + arg |
| 1069 |
|
| 1070 |
def insertData(self, offset, arg): |
| 1071 |
if offset < 0: |
| 1072 |
raise xml.dom.IndexSizeErr("offset cannot be negative") |
| 1073 |
if offset >= len(self.data): |
| 1074 |
raise xml.dom.IndexSizeErr("offset cannot be beyond end of data") |
| 1075 |
if arg: |
| 1076 |
self.data = "%s%s%s" % ( |
| 1077 |
self.data[:offset], arg, self.data[offset:]) |
| 1078 |
|
| 1079 |
def deleteData(self, offset, count): |
| 1080 |
if offset < 0: |
| 1081 |
raise xml.dom.IndexSizeErr("offset cannot be negative") |
| 1082 |
if offset >= len(self.data): |
| 1083 |
raise xml.dom.IndexSizeErr("offset cannot be beyond end of data") |
| 1084 |
if count < 0: |
| 1085 |
raise xml.dom.IndexSizeErr("count cannot be negative") |
| 1086 |
if count: |
| 1087 |
self.data = self.data[:offset] + self.data[offset+count:] |
| 1088 |
|
| 1089 |
def replaceData(self, offset, count, arg): |
| 1090 |
if offset < 0: |
| 1091 |
raise xml.dom.IndexSizeErr("offset cannot be negative") |
| 1092 |
if offset >= len(self.data): |
| 1093 |
raise xml.dom.IndexSizeErr("offset cannot be beyond end of data") |
| 1094 |
if count < 0: |
| 1095 |
raise xml.dom.IndexSizeErr("count cannot be negative") |
| 1096 |
if count: |
| 1097 |
self.data = "%s%s%s" % ( |
| 1098 |
self.data[:offset], arg, self.data[offset+count:]) |
| 1099 |
|
| 1100 |
defproperty(CharacterData, "length", doc="Length of the string data.") |
| 1101 |
|
| 1102 |
|
| 1103 |
class Text(CharacterData): |
| 1104 |
__slots__ = () |
| 1105 |
|
| 1106 |
nodeType = Node.TEXT_NODE |
| 1107 |
nodeName = "#text" |
| 1108 |
attributes = None |
| 1109 |
|
| 1110 |
def splitText(self, offset): |
| 1111 |
if offset < 0 or offset > len(self.data): |
| 1112 |
raise xml.dom.IndexSizeErr("illegal offset value") |
| 1113 |
newText = self.__class__() |
| 1114 |
newText.data = self.data[offset:] |
| 1115 |
newText.ownerDocument = self.ownerDocument |
| 1116 |
next = self.nextSibling |
| 1117 |
if self.parentNode and self in self.parentNode.childNodes: |
| 1118 |
if next is None: |
| 1119 |
self.parentNode.appendChild(newText) |
| 1120 |
else: |
| 1121 |
self.parentNode.insertBefore(newText, next) |
| 1122 |
self.data = self.data[:offset] |
| 1123 |
return newText |
| 1124 |
|
| 1125 |
def writexml(self, writer, indent="", addindent="", newl=""): |
| 1126 |
_write_data(writer, "%s%s%s" % (indent, self.data, newl), False) |
| 1127 |
|
| 1128 |
# DOM Level 3 (WD 9 April 2002) |
| 1129 |
|
| 1130 |
def _get_wholeText(self): |
| 1131 |
L = [self.data] |
| 1132 |
n = self.previousSibling |
| 1133 |
while n is not None: |
| 1134 |
if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): |
| 1135 |
L.insert(0, n.data) |
| 1136 |
n = n.previousSibling |
| 1137 |
else: |
| 1138 |
break |
| 1139 |
n = self.nextSibling |
| 1140 |
while n is not None: |
| 1141 |
if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): |
| 1142 |
L.append(n.data) |
| 1143 |
n = n.nextSibling |
| 1144 |
else: |
| 1145 |
break |
| 1146 |
return ''.join(L) |
| 1147 |
|
| 1148 |
def replaceWholeText(self, content): |
| 1149 |
# XXX This needs to be seriously changed if minidom ever |
| 1150 |
# supports EntityReference nodes. |
| 1151 |
parent = self.parentNode |
| 1152 |
n = self.previousSibling |
| 1153 |
while n is not None: |
| 1154 |
if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): |
| 1155 |
next = n.previousSibling |
| 1156 |
parent.removeChild(n) |
| 1157 |
n = next |
| 1158 |
else: |
| 1159 |
break |
| 1160 |
n = self.nextSibling |
| 1161 |
if not content: |
| 1162 |
parent.removeChild(self) |
| 1163 |
while n is not None: |
| 1164 |
if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): |
| 1165 |
next = n.nextSibling |
| 1166 |
parent.removeChild(n) |
| 1167 |
n = next |
| 1168 |
else: |
| 1169 |
break |
| 1170 |
if content: |
| 1171 |
self.data = content |
| 1172 |
return self |
| 1173 |
else: |
| 1174 |
return None |
| 1175 |
|
| 1176 |
def _get_isWhitespaceInElementContent(self): |
| 1177 |
if self.data.strip(): |
| 1178 |
return False |
| 1179 |
elem = _get_containing_element(self) |
| 1180 |
if elem is None: |
| 1181 |
return False |
| 1182 |
info = self.ownerDocument._get_elem_info(elem) |
| 1183 |
if info is None: |
| 1184 |
return False |
| 1185 |
else: |
| 1186 |
return info.isElementContent() |
| 1187 |
|
| 1188 |
defproperty(Text, "isWhitespaceInElementContent", |
| 1189 |
doc="True iff this text node contains only whitespace" |
| 1190 |
" and is in element content.") |
| 1191 |
defproperty(Text, "wholeText", |
| 1192 |
doc="The text of all logically-adjacent text nodes.") |
| 1193 |
|
| 1194 |
|
| 1195 |
def _get_containing_element(node): |
| 1196 |
c = node.parentNode |
| 1197 |
while c is not None: |
| 1198 |
if c.nodeType == Node.ELEMENT_NODE: |
| 1199 |
return c |
| 1200 |
c = c.parentNode |
| 1201 |
return None |
| 1202 |
|
| 1203 |
def _get_containing_entref(node): |
| 1204 |
c = node.parentNode |
| 1205 |
while c is not None: |
| 1206 |
if c.nodeType == Node.ENTITY_REFERENCE_NODE: |
| 1207 |
return c |
| 1208 |
c = c.parentNode |
| 1209 |
return None |
| 1210 |
|
| 1211 |
|
| 1212 |
class Comment(CharacterData): |
| 1213 |
nodeType = Node.COMMENT_NODE |
| 1214 |
nodeName = "#comment" |
| 1215 |
|
| 1216 |
def __init__(self, data): |
| 1217 |
CharacterData.__init__(self) |
| 1218 |
self._data = data |
| 1219 |
|
| 1220 |
def writexml(self, writer, indent="", addindent="", newl=""): |
| 1221 |
if "--" in self.data: |
| 1222 |
raise ValueError("'--' is not allowed in a comment node") |
| 1223 |
writer.write("%s<!--%s-->%s" % (indent, self.data, newl)) |
| 1224 |
|
| 1225 |
|
| 1226 |
class CDATASection(Text): |
| 1227 |
__slots__ = () |
| 1228 |
|
| 1229 |
nodeType = Node.CDATA_SECTION_NODE |
| 1230 |
nodeName = "#cdata-section" |
| 1231 |
|
| 1232 |
def writexml(self, writer, indent="", addindent="", newl=""): |
| 1233 |
if self.data.find("]]>") >= 0: |
| 1234 |
raise ValueError("']]>' not allowed in a CDATA section") |
| 1235 |
writer.write("<![CDATA[%s]]>" % self.data) |
| 1236 |
|
| 1237 |
|
| 1238 |
class ReadOnlySequentialNamedNodeMap(object): |
| 1239 |
__slots__ = '_seq', |
| 1240 |
|
| 1241 |
def __init__(self, seq=()): |
| 1242 |
# seq should be a list or tuple |
| 1243 |
self._seq = seq |
| 1244 |
|
| 1245 |
def __len__(self): |
| 1246 |
return len(self._seq) |
| 1247 |
|
| 1248 |
def _get_length(self): |
| 1249 |
return len(self._seq) |
| 1250 |
|
| 1251 |
def getNamedItem(self, name): |
| 1252 |
for n in self._seq: |
| 1253 |
if n.nodeName == name: |
| 1254 |
return n |
| 1255 |
|
| 1256 |
def getNamedItemNS(self, namespaceURI, localName): |
| 1257 |
for n in self._seq: |
| 1258 |
if n.namespaceURI == namespaceURI and n.localName == localName: |
| 1259 |
return n |
| 1260 |
|
| 1261 |
def __getitem__(self, name_or_tuple): |
| 1262 |
if isinstance(name_or_tuple, tuple): |
| 1263 |
node = self.getNamedItemNS(*name_or_tuple) |
| 1264 |
else: |
| 1265 |
node = self.getNamedItem(name_or_tuple) |
| 1266 |
if node is None: |
| 1267 |
raise KeyError(name_or_tuple) |
| 1268 |
return node |
| 1269 |
|
| 1270 |
def item(self, index): |
| 1271 |
if index < 0: |
| 1272 |
return None |
| 1273 |
try: |
| 1274 |
return self._seq[index] |
| 1275 |
except IndexError: |
| 1276 |
return None |
| 1277 |
|
| 1278 |
def removeNamedItem(self, name): |
| 1279 |
raise xml.dom.NoModificationAllowedErr( |
| 1280 |
"NamedNodeMap instance is read-only") |
| 1281 |
|
| 1282 |
def removeNamedItemNS(self, namespaceURI, localName): |
| 1283 |
raise xml.dom.NoModificationAllowedErr( |
| 1284 |
"NamedNodeMap instance is read-only") |
| 1285 |
|
| 1286 |
def setNamedItem(self, node): |
| 1287 |
raise xml.dom.NoModificationAllowedErr( |
| 1288 |
"NamedNodeMap instance is read-only") |
| 1289 |
|
| 1290 |
def setNamedItemNS(self, node): |
| 1291 |
raise xml.dom.NoModificationAllowedErr( |
| 1292 |
"NamedNodeMap instance is read-only") |
| 1293 |
|
| 1294 |
def __getstate__(self): |
| 1295 |
return [self._seq] |
| 1296 |
|
| 1297 |
def __setstate__(self, state): |
| 1298 |
self._seq = state[0] |
| 1299 |
|
| 1300 |
defproperty(ReadOnlySequentialNamedNodeMap, "length", |
| 1301 |
doc="Number of entries in the NamedNodeMap.") |
| 1302 |
|
| 1303 |
|
| 1304 |
class Identified: |
| 1305 |
"""Mix-in class that supports the publicId and systemId attributes.""" |
| 1306 |
|
| 1307 |
__slots__ = 'publicId', 'systemId' |
| 1308 |
|
| 1309 |
def _identified_mixin_init(self, publicId, systemId): |
| 1310 |
self.publicId = publicId |
| 1311 |
self.systemId = systemId |
| 1312 |
|
| 1313 |
def _get_publicId(self): |
| 1314 |
return self.publicId |
| 1315 |
|
| 1316 |
def _get_systemId(self): |
| 1317 |
return self.systemId |
| 1318 |
|
| 1319 |
class DocumentType(Identified, Childless, Node): |
| 1320 |
nodeType = Node.DOCUMENT_TYPE_NODE |
| 1321 |
nodeValue = None |
| 1322 |
name = None |
| 1323 |
publicId = None |
| 1324 |
systemId = None |
| 1325 |
internalSubset = None |
| 1326 |
|
| 1327 |
def __init__(self, qualifiedName): |
| 1328 |
self.entities = ReadOnlySequentialNamedNodeMap() |
| 1329 |
self.notations = ReadOnlySequentialNamedNodeMap() |
| 1330 |
if qualifiedName: |
| 1331 |
prefix, localname = _nssplit(qualifiedName) |
| 1332 |
self.name = localname |
| 1333 |
self.nodeName = self.name |
| 1334 |
|
| 1335 |
def _get_internalSubset(self): |
| 1336 |
return self.internalSubset |
| 1337 |
|
| 1338 |
def cloneNode(self, deep): |
| 1339 |
if self.ownerDocument is None: |
| 1340 |
# it's ok |
| 1341 |
clone = DocumentType(None) |
| 1342 |
clone.name = self.name |
| 1343 |
clone.nodeName = self.name |
| 1344 |
operation = xml.dom.UserDataHandler.NODE_CLONED |
| 1345 |
if deep: |
| 1346 |
clone.entities._seq = [] |
| 1347 |
clone.notations._seq = [] |
| 1348 |
for n in self.notations._seq: |
| 1349 |
notation = Notation(n.nodeName, n.publicId, n.systemId) |
| 1350 |
clone.notations._seq.append(notation) |
| 1351 |
n._call_user_data_handler(operation, n, notation) |
| 1352 |
for e in self.entities._seq: |
| 1353 |
entity = Entity(e.nodeName, e.publicId, e.systemId, |
| 1354 |
e.notationName) |
| 1355 |
entity.actualEncoding = e.actualEncoding |
| 1356 |
entity.encoding = e.encoding |
| 1357 |
entity.version = e.version |
| 1358 |
clone.entities._seq.append(entity) |
| 1359 |
e._call_user_data_handler(operation, e, entity) |
| 1360 |
self._call_user_data_handler(operation, self, clone) |
| 1361 |
return clone |
| 1362 |
else: |
| 1363 |
return None |
| 1364 |
|
| 1365 |
def writexml(self, writer, indent="", addindent="", newl=""): |
| 1366 |
writer.write("<!DOCTYPE ") |
| 1367 |
writer.write(self.name) |
| 1368 |
if self.publicId: |
| 1369 |
writer.write("%s PUBLIC '%s'%s '%s'" |
| 1370 |
% (newl, self.publicId, newl, self.systemId)) |
| 1371 |
elif self.systemId: |
| 1372 |
writer.write("%s SYSTEM '%s'" % (newl, self.systemId)) |
| 1373 |
if self.internalSubset is not None: |
| 1374 |
writer.write(" [") |
| 1375 |
writer.write(self.internalSubset) |
| 1376 |
writer.write("]") |
| 1377 |
writer.write(">"+newl) |
| 1378 |
|
| 1379 |
class Entity(Identified, Node): |
| 1380 |
attributes = None |
| 1381 |
nodeType = Node.ENTITY_NODE |
| 1382 |
nodeValue = None |
| 1383 |
|
| 1384 |
actualEncoding = None |
| 1385 |
encoding = None |
| 1386 |
version = None |
| 1387 |
|
| 1388 |
def __init__(self, name, publicId, systemId, notation): |
| 1389 |
self.nodeName = name |
| 1390 |
self.notationName = notation |
| 1391 |
self.childNodes = NodeList() |
| 1392 |
self._identified_mixin_init(publicId, systemId) |
| 1393 |
|
| 1394 |
def _get_actualEncoding(self): |
| 1395 |
return self.actualEncoding |
| 1396 |
|
| 1397 |
def _get_encoding(self): |
| 1398 |
return self.encoding |
| 1399 |
|
| 1400 |
def _get_version(self): |
| 1401 |
return self.version |
| 1402 |
|
| 1403 |
def appendChild(self, newChild): |
| 1404 |
raise xml.dom.HierarchyRequestErr( |
| 1405 |
"cannot append children to an entity node") |
| 1406 |
|
| 1407 |
def insertBefore(self, newChild, refChild): |
| 1408 |
raise xml.dom.HierarchyRequestErr( |
| 1409 |
"cannot insert children below an entity node") |
| 1410 |
|
| 1411 |
def removeChild(self, oldChild): |
| 1412 |
raise xml.dom.HierarchyRequestErr( |
| 1413 |
"cannot remove children from an entity node") |
| 1414 |
|
| 1415 |
def replaceChild(self, newChild, oldChild): |
| 1416 |
raise xml.dom.HierarchyRequestErr( |
| 1417 |
"cannot replace children of an entity node") |
| 1418 |
|
| 1419 |
class Notation(Identified, Childless, Node): |
| 1420 |
nodeType = Node.NOTATION_NODE |
| 1421 |
nodeValue = None |
| 1422 |
|
| 1423 |
def __init__(self, name, publicId, systemId): |
| 1424 |
self.nodeName = name |
| 1425 |
self._identified_mixin_init(publicId, systemId) |
| 1426 |
|
| 1427 |
|
| 1428 |
class DOMImplementation(DOMImplementationLS): |
| 1429 |
_features = [("core", "1.0"), |
| 1430 |
("core", "2.0"), |
| 1431 |
("core", None), |
| 1432 |
("xml", "1.0"), |
| 1433 |
("xml", "2.0"), |
| 1434 |
("xml", None), |
| 1435 |
("ls-load", "3.0"), |
| 1436 |
("ls-load", None), |
| 1437 |
] |
| 1438 |
|
| 1439 |
def hasFeature(self, feature, version): |
| 1440 |
if version == "": |
| 1441 |
version = None |
| 1442 |
return (feature.lower(), version) in self._features |
| 1443 |
|
| 1444 |
def createDocument(self, namespaceURI, qualifiedName, doctype): |
| 1445 |
if doctype and doctype.parentNode is not None: |
| 1446 |
raise xml.dom.WrongDocumentErr( |
| 1447 |
"doctype object owned by another DOM tree") |
| 1448 |
doc = self._create_document() |
| 1449 |
|
| 1450 |
add_root_element = not (namespaceURI is None |
| 1451 |
and qualifiedName is None |
| 1452 |
and doctype is None) |
| 1453 |
|
| 1454 |
if not qualifiedName and add_root_element: |
| 1455 |
# The spec is unclear what to raise here; SyntaxErr |
| 1456 |
# would be the other obvious candidate. Since Xerces raises |
| 1457 |
# InvalidCharacterErr, and since SyntaxErr is not listed |
| 1458 |
# for createDocument, that seems to be the better choice. |
| 1459 |
# XXX: need to check for illegal characters here and in |
| 1460 |
# createElement. |
| 1461 |
|
| 1462 |
# DOM Level III clears this up when talking about the return value |
| 1463 |
# of this function. If namespaceURI, qName and DocType are |
| 1464 |
# Null the document is returned without a document element |
| 1465 |
# Otherwise if doctype or namespaceURI are not None |
| 1466 |
# Then we go back to the above problem |
| 1467 |
raise xml.dom.InvalidCharacterErr("Element with no name") |
| 1468 |
|
| 1469 |
if add_root_element: |
| 1470 |
prefix, localname = _nssplit(qualifiedName) |
| 1471 |
if prefix == "xml" \ |
| 1472 |
and namespaceURI != "http://www.w3.org/XML/1998/namespace": |
| 1473 |
raise xml.dom.NamespaceErr("illegal use of 'xml' prefix") |
| 1474 |
if prefix and not namespaceURI: |
| 1475 |
raise xml.dom.NamespaceErr( |
| 1476 |
"illegal use of prefix without namespaces") |
| 1477 |
element = doc.createElementNS(namespaceURI, qualifiedName) |
| 1478 |
if doctype: |
| 1479 |
doc.appendChild(doctype) |
| 1480 |
doc.appendChild(element) |
| 1481 |
|
| 1482 |
if doctype: |
| 1483 |
doctype.parentNode = doctype.ownerDocument = doc |
| 1484 |
|
| 1485 |
doc.doctype = doctype |
| 1486 |
doc.implementation = self |
| 1487 |
return doc |
| 1488 |
|
| 1489 |
def createDocumentType(self, qualifiedName, publicId, systemId): |
| 1490 |
doctype = DocumentType(qualifiedName) |
| 1491 |
doctype.publicId = publicId |
| 1492 |
doctype.systemId = systemId |
| 1493 |
return doctype |
| 1494 |
|
| 1495 |
# DOM Level 3 (WD 9 April 2002) |
| 1496 |
|
| 1497 |
def getInterface(self, feature): |
| 1498 |
if self.hasFeature(feature, None): |
| 1499 |
return self |
| 1500 |
else: |
| 1501 |
return None |
| 1502 |
|
| 1503 |
# internal |
| 1504 |
def _create_document(self): |
| 1505 |
return Document() |
| 1506 |
|
| 1507 |
class ElementInfo(object): |
| 1508 |
"""Object that represents content-model information for an element. |
| 1509 |
|
| 1510 |
This implementation is not expected to be used in practice; DOM |
| 1511 |
builders should provide implementations which do the right thing |
| 1512 |
using information available to it. |
| 1513 |
|
| 1514 |
""" |
| 1515 |
|
| 1516 |
__slots__ = 'tagName', |
| 1517 |
|
| 1518 |
def __init__(self, name): |
| 1519 |
self.tagName = name |
| 1520 |
|
| 1521 |
def getAttributeType(self, aname): |
| 1522 |
return _no_type |
| 1523 |
|
| 1524 |
def getAttributeTypeNS(self, namespaceURI, localName): |
| 1525 |
return _no_type |
| 1526 |
|
| 1527 |
def isElementContent(self): |
| 1528 |
return False |
| 1529 |
|
| 1530 |
def isEmpty(self): |
| 1531 |
"""Returns true iff this element is declared to have an EMPTY |
| 1532 |
content model.""" |
| 1533 |
return False |
| 1534 |
|
| 1535 |
def isId(self, aname): |
| 1536 |
"""Returns true iff the named attribute is a DTD-style ID.""" |
| 1537 |
return False |
| 1538 |
|
| 1539 |
def isIdNS(self, namespaceURI, localName): |
| 1540 |
"""Returns true iff the identified attribute is a DTD-style ID.""" |
| 1541 |
return False |
| 1542 |
|
| 1543 |
def __getstate__(self): |
| 1544 |
return self.tagName |
| 1545 |
|
| 1546 |
def __setstate__(self, state): |
| 1547 |
self.tagName = state |
| 1548 |
|
| 1549 |
def _clear_id_cache(node): |
| 1550 |
if node.nodeType == Node.DOCUMENT_NODE: |
| 1551 |
node._id_cache.clear() |
| 1552 |
node._id_search_stack = None |
| 1553 |
elif node.ownerDocument: |
| 1554 |
node.ownerDocument._id_cache.clear() |
| 1555 |
node.ownerDocument._id_search_stack= None |
| 1556 |
|
| 1557 |
class Document(Node, DocumentLS): |
| 1558 |
__slots__ = ('_elem_info', 'doctype', |
| 1559 |
'_id_search_stack', 'childNodes', '_id_cache') |
| 1560 |
_child_node_types = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE, |
| 1561 |
Node.COMMENT_NODE, Node.DOCUMENT_TYPE_NODE) |
| 1562 |
|
| 1563 |
implementation = DOMImplementation() |
| 1564 |
nodeType = Node.DOCUMENT_NODE |
| 1565 |
nodeName = "#document" |
| 1566 |
nodeValue = None |
| 1567 |
attributes = None |
| 1568 |
parentNode = None |
| 1569 |
previousSibling = nextSibling = None |
| 1570 |
|
| 1571 |
|
| 1572 |
# Document attributes from Level 3 (WD 9 April 2002) |
| 1573 |
|
| 1574 |
actualEncoding = None |
| 1575 |
encoding = None |
| 1576 |
standalone = None |
| 1577 |
version = None |
| 1578 |
strictErrorChecking = False |
| 1579 |
errorHandler = None |
| 1580 |
documentURI = None |
| 1581 |
|
| 1582 |
_magic_id_count = 0 |
| 1583 |
|
| 1584 |
def __init__(self): |
| 1585 |
self.doctype = None |
| 1586 |
self.childNodes = NodeList() |
| 1587 |
# mapping of (namespaceURI, localName) -> ElementInfo |
| 1588 |
# and tagName -> ElementInfo |
| 1589 |
self._elem_info = {} |
| 1590 |
self._id_cache = {} |
| 1591 |
self._id_search_stack = None |
| 1592 |
|
| 1593 |
def _get_elem_info(self, element): |
| 1594 |
if element.namespaceURI: |
| 1595 |
key = element.namespaceURI, element.localName |
| 1596 |
else: |
| 1597 |
key = element.tagName |
| 1598 |
return self._elem_info.get(key) |
| 1599 |
|
| 1600 |
def _get_actualEncoding(self): |
| 1601 |
return self.actualEncoding |
| 1602 |
|
| 1603 |
def _get_doctype(self): |
| 1604 |
return self.doctype |
| 1605 |
|
| 1606 |
def _get_documentURI(self): |
| 1607 |
return self.documentURI |
| 1608 |
|
| 1609 |
def _get_encoding(self): |
| 1610 |
return self.encoding |
| 1611 |
|
| 1612 |
def _get_errorHandler(self): |
| 1613 |
return self.errorHandler |
| 1614 |
|
| 1615 |
def _get_standalone(self): |
| 1616 |
return self.standalone |
| 1617 |
|
| 1618 |
def _get_strictErrorChecking(self): |
| 1619 |
return self.strictErrorChecking |
| 1620 |
|
| 1621 |
def _get_version(self): |
| 1622 |
return self.version |
| 1623 |
|
| 1624 |
def appendChild(self, node): |
| 1625 |
if node.nodeType not in self._child_node_types: |
| 1626 |
raise xml.dom.HierarchyRequestErr( |
| 1627 |
"%s cannot be child of %s" % (repr(node), repr(self))) |
| 1628 |
if node.parentNode is not None: |
| 1629 |
# This needs to be done before the next test since this |
| 1630 |
# may *be* the document element, in which case it should |
| 1631 |
# end up re-ordered to the end. |
| 1632 |
node.parentNode.removeChild(node) |
| 1633 |
|
| 1634 |
if node.nodeType == Node.ELEMENT_NODE \ |
| 1635 |
and self._get_documentElement(): |
| 1636 |
raise xml.dom.HierarchyRequestErr( |
| 1637 |
"two document elements disallowed") |
| 1638 |
return Node.appendChild(self, node) |
| 1639 |
|
| 1640 |
def removeChild(self, oldChild): |
| 1641 |
try: |
| 1642 |
self.childNodes.remove(oldChild) |
| 1643 |
except ValueError: |
| 1644 |
raise xml.dom.NotFoundErr() |
| 1645 |
oldChild.nextSibling = oldChild.previousSibling = None |
| 1646 |
oldChild.parentNode = None |
| 1647 |
if self.documentElement is oldChild: |
| 1648 |
self.documentElement = None |
| 1649 |
|
| 1650 |
return oldChild |
| 1651 |
|
| 1652 |
def _get_documentElement(self): |
| 1653 |
for node in self.childNodes: |
| 1654 |
if node.nodeType == Node.ELEMENT_NODE: |
| 1655 |
return node |
| 1656 |
|
| 1657 |
def unlink(self): |
| 1658 |
if self.doctype is not None: |
| 1659 |
self.doctype.unlink() |
| 1660 |
self.doctype = None |
| 1661 |
Node.unlink(self) |
| 1662 |
|
| 1663 |
def cloneNode(self, deep): |
| 1664 |
if not deep: |
| 1665 |
return None |
| 1666 |
clone = self.implementation.createDocument(None, None, None) |
| 1667 |
clone.encoding = self.encoding |
| 1668 |
clone.standalone = self.standalone |
| 1669 |
clone.version = self.version |
| 1670 |
for n in self.childNodes: |
| 1671 |
childclone = _clone_node(n, deep, clone) |
| 1672 |
assert childclone.ownerDocument.isSameNode(clone) |
| 1673 |
clone.childNodes.append(childclone) |
| 1674 |
if childclone.nodeType == Node.DOCUMENT_NODE: |
| 1675 |
assert clone.documentElement is None |
| 1676 |
elif childclone.nodeType == Node.DOCUMENT_TYPE_NODE: |
| 1677 |
assert clone.doctype is None |
| 1678 |
clone.doctype = childclone |
| 1679 |
childclone.parentNode = clone |
| 1680 |
self._call_user_data_handler(xml.dom.UserDataHandler.NODE_CLONED, |
| 1681 |
self, clone) |
| 1682 |
return clone |
| 1683 |
|
| 1684 |
def createDocumentFragment(self): |
| 1685 |
d = DocumentFragment() |
| 1686 |
d.ownerDocument = self |
| 1687 |
return d |
| 1688 |
|
| 1689 |
def createElement(self, tagName): |
| 1690 |
e = Element(tagName) |
| 1691 |
e.ownerDocument = self |
| 1692 |
return e |
| 1693 |
|
| 1694 |
def createTextNode(self, data): |
| 1695 |
if not isinstance(data, str): |
| 1696 |
raise TypeError("node contents must be a string") |
| 1697 |
t = Text() |
| 1698 |
t.data = data |
| 1699 |
t.ownerDocument = self |
| 1700 |
return t |
| 1701 |
|
| 1702 |
def createCDATASection(self, data): |
| 1703 |
if not isinstance(data, str): |
| 1704 |
raise TypeError("node contents must be a string") |
| 1705 |
c = CDATASection() |
| 1706 |
c.data = data |
| 1707 |
c.ownerDocument = self |
| 1708 |
return c |
| 1709 |
|
| 1710 |
def createComment(self, data): |
| 1711 |
c = Comment(data) |
| 1712 |
c.ownerDocument = self |
| 1713 |
return c |
| 1714 |
|
| 1715 |
def createProcessingInstruction(self, target, data): |
| 1716 |
p = ProcessingInstruction(target, data) |
| 1717 |
p.ownerDocument = self |
| 1718 |
return p |
| 1719 |
|
| 1720 |
def createAttribute(self, qName): |
| 1721 |
a = Attr(qName) |
| 1722 |
a.ownerDocument = self |
| 1723 |
a.value = "" |
| 1724 |
return a |
| 1725 |
|
| 1726 |
def createElementNS(self, namespaceURI, qualifiedName): |
| 1727 |
prefix, localName = _nssplit(qualifiedName) |
| 1728 |
e = Element(qualifiedName, namespaceURI, prefix) |
| 1729 |
e.ownerDocument = self |
| 1730 |
return e |
| 1731 |
|
| 1732 |
def createAttributeNS(self, namespaceURI, qualifiedName): |
| 1733 |
prefix, localName = _nssplit(qualifiedName) |
| 1734 |
a = Attr(qualifiedName, namespaceURI, localName, prefix) |
| 1735 |
a.ownerDocument = self |
| 1736 |
a.value = "" |
| 1737 |
return a |
| 1738 |
|
| 1739 |
# A couple of implementation-specific helpers to create node types |
| 1740 |
# not supported by the W3C DOM specs: |
| 1741 |
|
| 1742 |
def _create_entity(self, name, publicId, systemId, notationName): |
| 1743 |
e = Entity(name, publicId, systemId, notationName) |
| 1744 |
e.ownerDocument = self |
| 1745 |
return e |
| 1746 |
|
| 1747 |
def _create_notation(self, name, publicId, systemId): |
| 1748 |
n = Notation(name, publicId, systemId) |
| 1749 |
n.ownerDocument = self |
| 1750 |
return n |
| 1751 |
|
| 1752 |
def getElementById(self, id): |
| 1753 |
if id in self._id_cache: |
| 1754 |
return self._id_cache[id] |
| 1755 |
if not (self._elem_info or self._magic_id_count): |
| 1756 |
return None |
| 1757 |
|
| 1758 |
stack = self._id_search_stack |
| 1759 |
if stack is None: |
| 1760 |
# we never searched before, or the cache has been cleared |
| 1761 |
stack = [self.documentElement] |
| 1762 |
self._id_search_stack = stack |
| 1763 |
elif not stack: |
| 1764 |
# Previous search was completed and cache is still valid; |
| 1765 |
# no matching node. |
| 1766 |
return None |
| 1767 |
|
| 1768 |
result = None |
| 1769 |
while stack: |
| 1770 |
node = stack.pop() |
| 1771 |
# add child elements to stack for continued searching |
| 1772 |
stack.extend([child for child in node.childNodes |
| 1773 |
if child.nodeType in _nodeTypes_with_children]) |
| 1774 |
# check this node |
| 1775 |
info = self._get_elem_info(node) |
| 1776 |
if info: |
| 1777 |
# We have to process all ID attributes before |
| 1778 |
# returning in order to get all the attributes set to |
| 1779 |
# be IDs using Element.setIdAttribute*(). |
| 1780 |
for attr in node.attributes.values(): |
| 1781 |
if attr.namespaceURI: |
| 1782 |
if info.isIdNS(attr.namespaceURI, attr.localName): |
| 1783 |
self._id_cache[attr.value] = node |
| 1784 |
if attr.value == id: |
| 1785 |
result = node |
| 1786 |
elif not node._magic_id_nodes: |
| 1787 |
break |
| 1788 |
elif info.isId(attr.name): |
| 1789 |
self._id_cache[attr.value] = node |
| 1790 |
if attr.value == id: |
| 1791 |
result = node |
| 1792 |
elif not node._magic_id_nodes: |
| 1793 |
break |
| 1794 |
elif attr._is_id: |
| 1795 |
self._id_cache[attr.value] = node |
| 1796 |
if attr.value == id: |
| 1797 |
result = node |
| 1798 |
elif node._magic_id_nodes == 1: |
| 1799 |
break |
| 1800 |
elif node._magic_id_nodes: |
| 1801 |
for attr in node.attributes.values(): |
| 1802 |
if attr._is_id: |
| 1803 |
self._id_cache[attr.value] = node |
| 1804 |
if attr.value == id: |
| 1805 |
result = node |
| 1806 |
if result is not None: |
| 1807 |
break |
| 1808 |
return result |
| 1809 |
|
| 1810 |
def getElementsByTagName(self, name): |
| 1811 |
return _get_elements_by_tagName_helper(self, name, NodeList()) |
| 1812 |
|
| 1813 |
def getElementsByTagNameNS(self, namespaceURI, localName): |
| 1814 |
return _get_elements_by_tagName_ns_helper( |
| 1815 |
self, namespaceURI, localName, NodeList()) |
| 1816 |
|
| 1817 |
def isSupported(self, feature, version): |
| 1818 |
return self.implementation.hasFeature(feature, version) |
| 1819 |
|
| 1820 |
def importNode(self, node, deep): |
| 1821 |
if node.nodeType == Node.DOCUMENT_NODE: |
| 1822 |
raise xml.dom.NotSupportedErr("cannot import document nodes") |
| 1823 |
elif node.nodeType == Node.DOCUMENT_TYPE_NODE: |
| 1824 |
raise xml.dom.NotSupportedErr("cannot import document type nodes") |
| 1825 |
return _clone_node(node, deep, self) |
| 1826 |
|
| 1827 |
def writexml(self, writer, indent="", addindent="", newl="", encoding=None, |
| 1828 |
standalone=None): |
| 1829 |
declarations = [] |
| 1830 |
|
| 1831 |
if encoding: |
| 1832 |
declarations.append(f'encoding="{encoding}"') |
| 1833 |
if standalone is not None: |
| 1834 |
declarations.append(f'standalone="{"yes" if standalone else "no"}"') |
| 1835 |
|
| 1836 |
writer.write(f'<?xml version="1.0" {" ".join(declarations)}?>{newl}') |
| 1837 |
|
| 1838 |
for node in self.childNodes: |
| 1839 |
node.writexml(writer, indent, addindent, newl) |
| 1840 |
|
| 1841 |
# DOM Level 3 (WD 9 April 2002) |
| 1842 |
|
| 1843 |
def renameNode(self, n, namespaceURI, name): |
| 1844 |
if n.ownerDocument is not self: |
| 1845 |
raise xml.dom.WrongDocumentErr( |
| 1846 |
"cannot rename nodes from other documents;\n" |
| 1847 |
"expected %s,\nfound %s" % (self, n.ownerDocument)) |
| 1848 |
if n.nodeType not in (Node.ELEMENT_NODE, Node.ATTRIBUTE_NODE): |
| 1849 |
raise xml.dom.NotSupportedErr( |
| 1850 |
"renameNode() only applies to element and attribute nodes") |
| 1851 |
if namespaceURI != EMPTY_NAMESPACE: |
| 1852 |
if ':' in name: |
| 1853 |
prefix, localName = name.split(':', 1) |
| 1854 |
if ( prefix == "xmlns" |
| 1855 |
and namespaceURI != xml.dom.XMLNS_NAMESPACE): |
| 1856 |
raise xml.dom.NamespaceErr( |
| 1857 |
"illegal use of 'xmlns' prefix") |
| 1858 |
else: |
| 1859 |
if ( name == "xmlns" |
| 1860 |
and namespaceURI != xml.dom.XMLNS_NAMESPACE |
| 1861 |
and n.nodeType == Node.ATTRIBUTE_NODE): |
| 1862 |
raise xml.dom.NamespaceErr( |
| 1863 |
"illegal use of the 'xmlns' attribute") |
| 1864 |
prefix = None |
| 1865 |
localName = name |
| 1866 |
else: |
| 1867 |
prefix = None |
| 1868 |
localName = None |
| 1869 |
if n.nodeType == Node.ATTRIBUTE_NODE: |
| 1870 |
element = n.ownerElement |
| 1871 |
if element is not None: |
| 1872 |
is_id = n._is_id |
| 1873 |
element.removeAttributeNode(n) |
| 1874 |
else: |
| 1875 |
element = None |
| 1876 |
n.prefix = prefix |
| 1877 |
n._localName = localName |
| 1878 |
n.namespaceURI = namespaceURI |
| 1879 |
n.nodeName = name |
| 1880 |
if n.nodeType == Node.ELEMENT_NODE: |
| 1881 |
n.tagName = name |
| 1882 |
else: |
| 1883 |
# attribute node |
| 1884 |
n.name = name |
| 1885 |
if element is not None: |
| 1886 |
element.setAttributeNode(n) |
| 1887 |
if is_id: |
| 1888 |
element.setIdAttributeNode(n) |
| 1889 |
# It's not clear from a semantic perspective whether we should |
| 1890 |
# call the user data handlers for the NODE_RENAMED event since |
| 1891 |
# we're re-using the existing node. The draft spec has been |
| 1892 |
# interpreted as meaning "no, don't call the handler unless a |
| 1893 |
# new node is created." |
| 1894 |
return n |
| 1895 |
|
| 1896 |
defproperty(Document, "documentElement", |
| 1897 |
doc="Top-level element of this document.") |
| 1898 |
|
| 1899 |
|
| 1900 |
def _clone_node(node, deep, newOwnerDocument): |
| 1901 |
""" |
| 1902 |
Clone a node and give it the new owner document. |
| 1903 |
Called by Node.cloneNode and Document.importNode |
| 1904 |
""" |
| 1905 |
if node.ownerDocument.isSameNode(newOwnerDocument): |
| 1906 |
operation = xml.dom.UserDataHandler.NODE_CLONED |
| 1907 |
else: |
| 1908 |
operation = xml.dom.UserDataHandler.NODE_IMPORTED |
| 1909 |
if node.nodeType == Node.ELEMENT_NODE: |
| 1910 |
clone = newOwnerDocument.createElementNS(node.namespaceURI, |
| 1911 |
node.nodeName) |
| 1912 |
for attr in node.attributes.values(): |
| 1913 |
clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value) |
| 1914 |
a = clone.getAttributeNodeNS(attr.namespaceURI, attr.localName) |
| 1915 |
a.specified = attr.specified |
| 1916 |
|
| 1917 |
if deep: |
| 1918 |
for child in node.childNodes: |
| 1919 |
c = _clone_node(child, deep, newOwnerDocument) |
| 1920 |
clone.appendChild(c) |
| 1921 |
|
| 1922 |
elif node.nodeType == Node.DOCUMENT_FRAGMENT_NODE: |
| 1923 |
clone = newOwnerDocument.createDocumentFragment() |
| 1924 |
if deep: |
| 1925 |
for child in node.childNodes: |
| 1926 |
c = _clone_node(child, deep, newOwnerDocument) |
| 1927 |
clone.appendChild(c) |
| 1928 |
|
| 1929 |
elif node.nodeType == Node.TEXT_NODE: |
| 1930 |
clone = newOwnerDocument.createTextNode(node.data) |
| 1931 |
elif node.nodeType == Node.CDATA_SECTION_NODE: |
| 1932 |
clone = newOwnerDocument.createCDATASection(node.data) |
| 1933 |
elif node.nodeType == Node.PROCESSING_INSTRUCTION_NODE: |
| 1934 |
clone = newOwnerDocument.createProcessingInstruction(node.target, |
| 1935 |
node.data) |
| 1936 |
elif node.nodeType == Node.COMMENT_NODE: |
| 1937 |
clone = newOwnerDocument.createComment(node.data) |
| 1938 |
elif node.nodeType == Node.ATTRIBUTE_NODE: |
| 1939 |
clone = newOwnerDocument.createAttributeNS(node.namespaceURI, |
| 1940 |
node.nodeName) |
| 1941 |
clone.specified = True |
| 1942 |
clone.value = node.value |
| 1943 |
elif node.nodeType == Node.DOCUMENT_TYPE_NODE: |
| 1944 |
assert node.ownerDocument is not newOwnerDocument |
| 1945 |
operation = xml.dom.UserDataHandler.NODE_IMPORTED |
| 1946 |
clone = newOwnerDocument.implementation.createDocumentType( |
| 1947 |
node.name, node.publicId, node.systemId) |
| 1948 |
clone.ownerDocument = newOwnerDocument |
| 1949 |
if deep: |
| 1950 |
clone.entities._seq = [] |
| 1951 |
clone.notations._seq = [] |
| 1952 |
for n in node.notations._seq: |
| 1953 |
notation = Notation(n.nodeName, n.publicId, n.systemId) |
| 1954 |
notation.ownerDocument = newOwnerDocument |
| 1955 |
clone.notations._seq.append(notation) |
| 1956 |
if hasattr(n, '_call_user_data_handler'): |
| 1957 |
n._call_user_data_handler(operation, n, notation) |
| 1958 |
for e in node.entities._seq: |
| 1959 |
entity = Entity(e.nodeName, e.publicId, e.systemId, |
| 1960 |
e.notationName) |
| 1961 |
entity.actualEncoding = e.actualEncoding |
| 1962 |
entity.encoding = e.encoding |
| 1963 |
entity.version = e.version |
| 1964 |
entity.ownerDocument = newOwnerDocument |
| 1965 |
clone.entities._seq.append(entity) |
| 1966 |
if hasattr(e, '_call_user_data_handler'): |
| 1967 |
e._call_user_data_handler(operation, e, entity) |
| 1968 |
else: |
| 1969 |
# Note the cloning of Document and DocumentType nodes is |
| 1970 |
# implementation specific. minidom handles those cases |
| 1971 |
# directly in the cloneNode() methods. |
| 1972 |
raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node)) |
| 1973 |
|
| 1974 |
# Check for _call_user_data_handler() since this could conceivably |
| 1975 |
# used with other DOM implementations (one of the FourThought |
| 1976 |
# DOMs, perhaps?). |
| 1977 |
if hasattr(node, '_call_user_data_handler'): |
| 1978 |
node._call_user_data_handler(operation, node, clone) |
| 1979 |
return clone |
| 1980 |
|
| 1981 |
|
| 1982 |
def _nssplit(qualifiedName): |
| 1983 |
fields = qualifiedName.split(':', 1) |
| 1984 |
if len(fields) == 2: |
| 1985 |
return fields |
| 1986 |
else: |
| 1987 |
return (None, fields[0]) |
| 1988 |
|
| 1989 |
|
| 1990 |
def _do_pulldom_parse(func, args, kwargs): |
| 1991 |
events = func(*args, **kwargs) |
| 1992 |
toktype, rootNode = events.getEvent() |
| 1993 |
events.expandNode(rootNode) |
| 1994 |
events.clear() |
| 1995 |
return rootNode |
| 1996 |
|
| 1997 |
def parse(file, parser=None, bufsize=None): |
| 1998 |
"""Parse a file into a DOM by filename or file object.""" |
| 1999 |
if parser is None and not bufsize: |
| 2000 |
from xml.dom import expatbuilder |
| 2001 |
return expatbuilder.parse(file) |
| 2002 |
else: |
| 2003 |
from xml.dom import pulldom |
| 2004 |
return _do_pulldom_parse(pulldom.parse, (file,), |
| 2005 |
{'parser': parser, 'bufsize': bufsize}) |
| 2006 |
|
| 2007 |
def parseString(string, parser=None): |
| 2008 |
"""Parse a file into a DOM from a string.""" |
| 2009 |
if parser is None: |
| 2010 |
from xml.dom import expatbuilder |
| 2011 |
return expatbuilder.parseString(string) |
| 2012 |
else: |
| 2013 |
from xml.dom import pulldom |
| 2014 |
return _do_pulldom_parse(pulldom.parseString, (string,), |
| 2015 |
{'parser': parser}) |
| 2016 |
|
| 2017 |
def getDOMImplementation(features=None): |
| 2018 |
if features: |
| 2019 |
if isinstance(features, str): |
| 2020 |
features = domreg._parse_feature_string(features) |
| 2021 |
for f, v in features: |
| 2022 |
if not Document.implementation.hasFeature(f, v): |
| 2023 |
return None |
| 2024 |
return Document.implementation |