paulb@18 | 1 | #!/usr/bin/env python |
paulb@18 | 2 | |
paulb@18 | 3 | """ |
paulb@75 | 4 | DOM wrapper around libxml2, specifically the libxml2mod Python extension module. |
paulb@188 | 5 | |
paulb@324 | 6 | Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Paul Boddie <paul@boddie.org.uk> |
paulb@188 | 7 | |
paulb@293 | 8 | This program is free software; you can redistribute it and/or modify it under |
paulb@293 | 9 | the terms of the GNU Lesser General Public License as published by the Free |
paulb@293 | 10 | Software Foundation; either version 3 of the License, or (at your option) any |
paulb@293 | 11 | later version. |
paulb@188 | 12 | |
paulb@293 | 13 | This program is distributed in the hope that it will be useful, but WITHOUT |
paulb@293 | 14 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS |
paulb@293 | 15 | FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more |
paulb@293 | 16 | details. |
paulb@188 | 17 | |
paulb@293 | 18 | You should have received a copy of the GNU Lesser General Public License along |
paulb@293 | 19 | with this program. If not, see <http://www.gnu.org/licenses/>. |
paulb@18 | 20 | """ |
paulb@18 | 21 | |
paulb@324 | 22 | __version__ = "0.4.6" |
paulb@27 | 23 | |
paulb@72 | 24 | from libxml2dom.macrolib import * |
paulb@72 | 25 | from libxml2dom.macrolib import \ |
paulb@72 | 26 | createDocument as Node_createDocument, \ |
paulb@72 | 27 | parseString as Node_parseString, parseURI as Node_parseURI, \ |
paulb@72 | 28 | parseFile as Node_parseFile, \ |
paulb@72 | 29 | toString as Node_toString, toStream as Node_toStream, \ |
paulb@72 | 30 | toFile as Node_toFile |
paulb@232 | 31 | import urllib # for parseURI in HTML mode |
paulb@262 | 32 | import xml.dom # for getElementById |
paulb@18 | 33 | |
paulb@301 | 34 | # Standard namespaces. |
paulb@301 | 35 | |
paulb@301 | 36 | XML_NAMESPACE = xml.dom.XML_NAMESPACE |
paulb@301 | 37 | |
paulb@301 | 38 | # Default namespace bindings for XPath. |
paulb@301 | 39 | |
paulb@301 | 40 | default_ns = { |
paulb@301 | 41 | "xml" : XML_NAMESPACE |
paulb@301 | 42 | } |
paulb@301 | 43 | |
paulb@218 | 44 | class Implementation(object): |
paulb@218 | 45 | |
paulb@218 | 46 | "Contains an abstraction over the DOM implementation." |
paulb@218 | 47 | |
paulb@218 | 48 | def createDocumentType(self, localName, publicId, systemId): |
paulb@218 | 49 | return DocumentType(localName, publicId, systemId) |
paulb@218 | 50 | |
paulb@218 | 51 | def createDocument(self, namespaceURI, localName, doctype): |
paulb@218 | 52 | return Document(Node_createDocument(namespaceURI, localName, doctype), self) |
paulb@218 | 53 | |
paulb@236 | 54 | # Wrapping of documents. |
paulb@236 | 55 | |
paulb@236 | 56 | def adoptDocument(self, node): |
paulb@236 | 57 | return Document(node, self) |
paulb@236 | 58 | |
paulb@218 | 59 | # Factory functions. |
paulb@218 | 60 | |
paulb@218 | 61 | def get_node(self, _node, context_node): |
paulb@218 | 62 | if Node_nodeType(_node) == context_node.DOCUMENT_NODE: |
paulb@218 | 63 | return context_node.ownerDocument |
paulb@218 | 64 | elif Node_nodeType(_node) == context_node.ATTRIBUTE_NODE: |
paulb@218 | 65 | return Attribute(_node, self, context_node.ownerDocument, context_node) |
paulb@218 | 66 | else: |
paulb@218 | 67 | return Node(_node, self, context_node.ownerDocument) |
paulb@218 | 68 | |
paulb@240 | 69 | def get_node_or_none(self, _node, context_node): |
paulb@240 | 70 | if _node is None: |
paulb@240 | 71 | return None |
paulb@240 | 72 | else: |
paulb@240 | 73 | return self.get_node(_node, context_node) |
paulb@240 | 74 | |
paulb@86 | 75 | # Attribute and node list wrappers. |
paulb@18 | 76 | |
paulb@18 | 77 | class NamedNodeMap(object): |
paulb@18 | 78 | |
paulb@75 | 79 | """ |
paulb@75 | 80 | A wrapper around Node objects providing DOM and dictionary convenience |
paulb@75 | 81 | methods. |
paulb@75 | 82 | """ |
paulb@75 | 83 | |
paulb@256 | 84 | def __init__(self, node, impl): |
paulb@18 | 85 | self.node = node |
paulb@256 | 86 | self.impl = impl |
paulb@18 | 87 | |
paulb@18 | 88 | def getNamedItem(self, name): |
paulb@72 | 89 | return self.node.getAttributeNode(name) |
paulb@18 | 90 | |
paulb@18 | 91 | def getNamedItemNS(self, ns, localName): |
paulb@72 | 92 | return self.node.getAttributeNodeNS(ns, localName) |
paulb@18 | 93 | |
paulb@18 | 94 | def setNamedItem(self, node): |
paulb@91 | 95 | try: |
paulb@91 | 96 | old = self.getNamedItem(node.nodeName) |
paulb@91 | 97 | except KeyError: |
paulb@91 | 98 | old = None |
paulb@86 | 99 | self.node.setAttributeNode(node) |
paulb@91 | 100 | return old |
paulb@18 | 101 | |
paulb@18 | 102 | def setNamedItemNS(self, node): |
paulb@91 | 103 | try: |
paulb@91 | 104 | old = self.getNamedItemNS(node.namespaceURI, node.localName) |
paulb@91 | 105 | except KeyError: |
paulb@91 | 106 | old = None |
paulb@86 | 107 | self.node.setAttributeNodeNS(node) |
paulb@91 | 108 | return old |
paulb@91 | 109 | |
paulb@91 | 110 | def removeNamedItem(self, name): |
paulb@91 | 111 | try: |
paulb@91 | 112 | old = self.getNamedItem(name) |
paulb@91 | 113 | except KeyError: |
paulb@91 | 114 | old = None |
paulb@91 | 115 | self.node.removeAttribute(name) |
paulb@91 | 116 | return old |
paulb@91 | 117 | |
paulb@91 | 118 | def removeNamedItemNS(self, ns, localName): |
paulb@91 | 119 | try: |
paulb@91 | 120 | old = self.getNamedItemNS(ns, localName) |
paulb@91 | 121 | except KeyError: |
paulb@91 | 122 | old = None |
paulb@91 | 123 | self.node.removeAttributeNS(ns, localName) |
paulb@91 | 124 | return old |
paulb@86 | 125 | |
paulb@276 | 126 | # Iterator emulation. |
paulb@276 | 127 | |
paulb@276 | 128 | def __iter__(self): |
paulb@276 | 129 | return NamedNodeMapIterator(self) |
paulb@276 | 130 | |
paulb@86 | 131 | # Dictionary emulation methods. |
paulb@18 | 132 | |
paulb@18 | 133 | def __getitem__(self, name): |
paulb@18 | 134 | return self.getNamedItem(name) |
paulb@18 | 135 | |
paulb@18 | 136 | def __setitem__(self, name, node): |
paulb@18 | 137 | if name == node.nodeName: |
paulb@18 | 138 | self.setNamedItem(node) |
paulb@18 | 139 | else: |
paulb@18 | 140 | raise KeyError, name |
paulb@18 | 141 | |
paulb@18 | 142 | def __delitem__(self, name): |
paulb@18 | 143 | # NOTE: To be implemented. |
paulb@18 | 144 | pass |
paulb@18 | 145 | |
paulb@18 | 146 | def values(self): |
paulb@218 | 147 | return [Attribute(_node, self.impl, self.node.ownerDocument) for _node in Node_attributes(self.node.as_native_node()).values()] |
paulb@18 | 148 | |
paulb@18 | 149 | def keys(self): |
paulb@18 | 150 | return [(attr.namespaceURI, attr.localName) for attr in self.values()] |
paulb@18 | 151 | |
paulb@18 | 152 | def items(self): |
paulb@18 | 153 | return [((attr.namespaceURI, attr.localName), attr) for attr in self.values()] |
paulb@18 | 154 | |
paulb@18 | 155 | def __repr__(self): |
paulb@18 | 156 | return str(self) |
paulb@18 | 157 | |
paulb@18 | 158 | def __str__(self): |
paulb@18 | 159 | return "{%s}" % ",\n".join(["%s : %s" % (repr(key), repr(value)) for key, value in self.items()]) |
paulb@18 | 160 | |
paulb@198 | 161 | def _length(self): |
paulb@198 | 162 | return len(self.values()) |
paulb@198 | 163 | |
paulb@198 | 164 | length = property(_length) |
paulb@198 | 165 | |
paulb@276 | 166 | class NamedNodeMapIterator(object): |
paulb@276 | 167 | |
paulb@276 | 168 | "An iterator over a NamedNodeMap." |
paulb@276 | 169 | |
paulb@276 | 170 | def __init__(self, nodemap): |
paulb@276 | 171 | self.nodemap = nodemap |
paulb@276 | 172 | self.items = self.nodemap.items() |
paulb@276 | 173 | |
paulb@276 | 174 | def next(self): |
paulb@276 | 175 | if self.items: |
paulb@276 | 176 | current = self.items[0][1] |
paulb@276 | 177 | self.items = self.items[1:] |
paulb@276 | 178 | return current |
paulb@276 | 179 | else: |
paulb@276 | 180 | raise StopIteration |
paulb@276 | 181 | |
paulb@86 | 182 | class NodeList(list): |
paulb@86 | 183 | |
paulb@86 | 184 | "A wrapper around node lists." |
paulb@86 | 185 | |
paulb@86 | 186 | def item(self, index): |
paulb@86 | 187 | return self[index] |
paulb@86 | 188 | |
paulb@198 | 189 | def _length(self): |
paulb@86 | 190 | return len(self) |
paulb@86 | 191 | |
paulb@198 | 192 | length = property(_length) |
paulb@198 | 193 | |
paulb@86 | 194 | # Node classes. |
paulb@86 | 195 | |
paulb@18 | 196 | class Node(object): |
paulb@18 | 197 | |
paulb@75 | 198 | """ |
paulb@75 | 199 | A DOM-style wrapper around libxml2mod objects. |
paulb@75 | 200 | """ |
paulb@75 | 201 | |
paulb@81 | 202 | ATTRIBUTE_NODE = xml.dom.Node.ATTRIBUTE_NODE |
paulb@81 | 203 | COMMENT_NODE = xml.dom.Node.COMMENT_NODE |
paulb@81 | 204 | DOCUMENT_NODE = xml.dom.Node.DOCUMENT_NODE |
paulb@81 | 205 | DOCUMENT_TYPE_NODE = xml.dom.Node.DOCUMENT_TYPE_NODE |
paulb@81 | 206 | ELEMENT_NODE = xml.dom.Node.ELEMENT_NODE |
paulb@81 | 207 | ENTITY_NODE = xml.dom.Node.ENTITY_NODE |
paulb@81 | 208 | ENTITY_REFERENCE_NODE = xml.dom.Node.ENTITY_REFERENCE_NODE |
paulb@81 | 209 | NOTATION_NODE = xml.dom.Node.NOTATION_NODE |
paulb@81 | 210 | PROCESSING_INSTRUCTION_NODE = xml.dom.Node.PROCESSING_INSTRUCTION_NODE |
paulb@81 | 211 | TEXT_NODE = xml.dom.Node.TEXT_NODE |
paulb@81 | 212 | |
paulb@223 | 213 | def __init__(self, node, impl=None, ownerDocument=None): |
paulb@18 | 214 | self._node = node |
paulb@223 | 215 | self.impl = impl or default_impl |
paulb@75 | 216 | self.ownerDocument = ownerDocument |
paulb@18 | 217 | |
paulb@18 | 218 | def as_native_node(self): |
paulb@18 | 219 | return self._node |
paulb@18 | 220 | |
paulb@18 | 221 | def _nodeType(self): |
paulb@72 | 222 | return Node_nodeType(self._node) |
paulb@18 | 223 | |
paulb@18 | 224 | def _childNodes(self): |
paulb@18 | 225 | |
paulb@18 | 226 | # NOTE: Consider a generator instead. |
paulb@18 | 227 | |
paulb@218 | 228 | return NodeList([self.impl.get_node(_node, self) for _node in Node_childNodes(self._node)]) |
paulb@18 | 229 | |
paulb@276 | 230 | def _firstChild(self): |
paulb@276 | 231 | return (self.childNodes or [None])[0] |
paulb@276 | 232 | |
paulb@276 | 233 | def _lastChild(self): |
paulb@276 | 234 | return (self.childNodes or [None])[-1] |
paulb@276 | 235 | |
paulb@18 | 236 | def _attributes(self): |
paulb@256 | 237 | return NamedNodeMap(self, self.impl) |
paulb@18 | 238 | |
paulb@18 | 239 | def _namespaceURI(self): |
paulb@72 | 240 | return Node_namespaceURI(self._node) |
paulb@18 | 241 | |
paulb@236 | 242 | def _textContent(self): |
paulb@236 | 243 | return Node_textContent(self._node) |
paulb@236 | 244 | |
paulb@18 | 245 | def _nodeValue(self): |
paulb@223 | 246 | if self.nodeType in null_value_node_types: |
paulb@223 | 247 | return None |
paulb@72 | 248 | return Node_nodeValue(self._node) |
paulb@18 | 249 | |
paulb@86 | 250 | def _setNodeValue(self, value): |
paulb@86 | 251 | Node_setNodeValue(self._node, value) |
paulb@86 | 252 | |
paulb@18 | 253 | def _prefix(self): |
paulb@72 | 254 | return Node_prefix(self._node) |
paulb@18 | 255 | |
paulb@18 | 256 | def _nodeName(self): |
paulb@72 | 257 | return Node_nodeName(self._node) |
paulb@18 | 258 | |
paulb@18 | 259 | def _tagName(self): |
paulb@72 | 260 | return Node_tagName(self._node) |
paulb@18 | 261 | |
paulb@18 | 262 | def _localName(self): |
paulb@72 | 263 | return Node_localName(self._node) |
paulb@18 | 264 | |
paulb@18 | 265 | def _parentNode(self): |
paulb@240 | 266 | return self.impl.get_node_or_none(Node_parentNode(self._node), self) |
paulb@18 | 267 | |
paulb@24 | 268 | def _previousSibling(self): |
paulb@240 | 269 | return self.impl.get_node_or_none(Node_previousSibling(self._node), self) |
paulb@24 | 270 | |
paulb@18 | 271 | def _nextSibling(self): |
paulb@240 | 272 | return self.impl.get_node_or_none(Node_nextSibling(self._node), self) |
paulb@18 | 273 | |
paulb@154 | 274 | def _doctype(self): |
paulb@276 | 275 | _doctype = Node_doctype(self._node) |
paulb@276 | 276 | if _doctype is not None: |
paulb@276 | 277 | return self.impl.get_node(_doctype, self) |
paulb@276 | 278 | else: |
paulb@276 | 279 | return None |
paulb@154 | 280 | |
paulb@154 | 281 | def _publicId(self): |
paulb@154 | 282 | # NOTE: To be fixed when the libxml2mod API has been figured out. |
paulb@154 | 283 | if self.nodeType != self.DOCUMENT_TYPE_NODE: |
paulb@154 | 284 | return None |
paulb@154 | 285 | declaration = self.toString() |
paulb@154 | 286 | return self._findId(declaration, "PUBLIC") |
paulb@154 | 287 | |
paulb@154 | 288 | def _systemId(self): |
paulb@154 | 289 | # NOTE: To be fixed when the libxml2mod API has been figured out. |
paulb@154 | 290 | if self.nodeType != self.DOCUMENT_TYPE_NODE: |
paulb@154 | 291 | return None |
paulb@154 | 292 | declaration = self.toString() |
paulb@154 | 293 | if self._findId(declaration, "PUBLIC"): |
paulb@154 | 294 | return self._findIdValue(declaration, 0) |
paulb@154 | 295 | return self._findId(declaration, "SYSTEM") |
paulb@154 | 296 | |
paulb@154 | 297 | # NOTE: To be removed when the libxml2mod API has been figured out. |
paulb@154 | 298 | |
paulb@154 | 299 | def _findId(self, declaration, identifier): |
paulb@154 | 300 | i = declaration.find(identifier) |
paulb@154 | 301 | if i == -1: |
paulb@154 | 302 | return None |
paulb@154 | 303 | return self._findIdValue(declaration, i) |
paulb@154 | 304 | |
paulb@154 | 305 | def _findIdValue(self, declaration, i): |
paulb@154 | 306 | q = declaration.find('"', i) |
paulb@154 | 307 | if q == -1: |
paulb@154 | 308 | return None |
paulb@154 | 309 | q2 = declaration.find('"', q + 1) |
paulb@154 | 310 | if q2 == -1: |
paulb@154 | 311 | return None |
paulb@154 | 312 | return declaration[q+1:q2] |
paulb@154 | 313 | |
paulb@18 | 314 | def hasAttributeNS(self, ns, localName): |
paulb@72 | 315 | return Node_hasAttributeNS(self._node, ns, localName) |
paulb@18 | 316 | |
paulb@18 | 317 | def hasAttribute(self, name): |
paulb@72 | 318 | return Node_hasAttribute(self._node, name) |
paulb@18 | 319 | |
paulb@18 | 320 | def getAttributeNS(self, ns, localName): |
paulb@72 | 321 | return Node_getAttributeNS(self._node, ns, localName) |
paulb@18 | 322 | |
paulb@18 | 323 | def getAttribute(self, name): |
paulb@72 | 324 | return Node_getAttribute(self._node, name) |
paulb@18 | 325 | |
paulb@18 | 326 | def getAttributeNodeNS(self, ns, localName): |
paulb@218 | 327 | return Attribute(Node_getAttributeNodeNS(self._node, ns, localName), self.impl, self.ownerDocument, self) |
paulb@18 | 328 | |
paulb@18 | 329 | def getAttributeNode(self, localName): |
paulb@218 | 330 | return Attribute(Node_getAttributeNode(self._node, localName), self.impl, self.ownerDocument, self) |
paulb@18 | 331 | |
paulb@18 | 332 | def setAttributeNS(self, ns, name, value): |
paulb@72 | 333 | Node_setAttributeNS(self._node, ns, name, value) |
paulb@18 | 334 | |
paulb@18 | 335 | def setAttribute(self, name, value): |
paulb@72 | 336 | Node_setAttribute(self._node, name, value) |
paulb@18 | 337 | |
paulb@86 | 338 | def setAttributeNodeNS(self, node): |
paulb@88 | 339 | Node_setAttributeNodeNS(self._node, node._node) |
paulb@18 | 340 | |
paulb@86 | 341 | def setAttributeNode(self, node): |
paulb@88 | 342 | Node_setAttributeNode(self._node, node._node) |
paulb@18 | 343 | |
paulb@91 | 344 | def removeAttributeNS(self, ns, localName): |
paulb@91 | 345 | Node_removeAttributeNS(self._node, ns, localName) |
paulb@91 | 346 | |
paulb@91 | 347 | def removeAttribute(self, name): |
paulb@91 | 348 | Node_removeAttribute(self._node, name) |
paulb@91 | 349 | |
paulb@18 | 350 | def createElementNS(self, ns, name): |
paulb@218 | 351 | return self.impl.get_node(Node_createElementNS(self._node, ns, name), self) |
paulb@18 | 352 | |
paulb@18 | 353 | def createElement(self, name): |
paulb@218 | 354 | return self.impl.get_node(Node_createElement(self._node, name), self) |
paulb@18 | 355 | |
paulb@88 | 356 | def createAttributeNS(self, ns, name): |
paulb@88 | 357 | tmp = self.createElement("tmp") |
paulb@218 | 358 | return Attribute(Node_createAttributeNS(tmp._node, self.impl, ns, name)) |
paulb@18 | 359 | |
paulb@88 | 360 | def createAttribute(self, name): |
paulb@88 | 361 | tmp = self.createElement("tmp") |
paulb@218 | 362 | return Attribute(Node_createAttribute(tmp._node, name), self.impl) |
paulb@18 | 363 | |
paulb@18 | 364 | def createTextNode(self, value): |
paulb@218 | 365 | return self.impl.get_node(Node_createTextNode(self._node, value), self) |
paulb@18 | 366 | |
paulb@34 | 367 | def createComment(self, value): |
paulb@218 | 368 | return self.impl.get_node(Node_createComment(self._node, value), self) |
paulb@18 | 369 | |
paulb@251 | 370 | def createCDATASection(self, value): |
paulb@251 | 371 | return self.impl.get_node(Node_createCDATASection(self._node, value), self) |
paulb@251 | 372 | |
paulb@18 | 373 | def importNode(self, node, deep): |
paulb@72 | 374 | if hasattr(node, "as_native_node"): |
paulb@218 | 375 | return self.impl.get_node(Node_importNode(self._node, node.as_native_node(), deep), self) |
paulb@72 | 376 | else: |
paulb@218 | 377 | return self.impl.get_node(Node_importNode_DOM(self._node, node, deep), self) |
paulb@18 | 378 | |
paulb@208 | 379 | def cloneNode(self, deep): |
paulb@208 | 380 | # This takes advantage of the ubiquity of importNode (in spite of the DOM specification). |
paulb@208 | 381 | return self.importNode(self, deep) |
paulb@208 | 382 | |
paulb@18 | 383 | def insertBefore(self, tmp, oldNode): |
paulb@276 | 384 | if tmp.ownerDocument != self.ownerDocument: |
paulb@276 | 385 | raise xml.dom.DOMException(xml.dom.WRONG_DOCUMENT_ERR) |
paulb@276 | 386 | if oldNode.parentNode != self: |
paulb@276 | 387 | raise xml.dom.DOMException(xml.dom.NOT_FOUND_ERR) |
paulb@72 | 388 | if hasattr(tmp, "as_native_node"): |
paulb@218 | 389 | return self.impl.get_node(Node_insertBefore(self._node, tmp.as_native_node(), oldNode.as_native_node()), self) |
paulb@18 | 390 | else: |
paulb@218 | 391 | return self.impl.get_node(Node_insertBefore(self._node, tmp, oldNode.as_native_node()), self) |
paulb@18 | 392 | |
paulb@18 | 393 | def replaceChild(self, tmp, oldNode): |
paulb@276 | 394 | if tmp.ownerDocument != self.ownerDocument: |
paulb@276 | 395 | raise xml.dom.DOMException(xml.dom.WRONG_DOCUMENT_ERR) |
paulb@276 | 396 | if oldNode.parentNode != self: |
paulb@276 | 397 | raise xml.dom.DOMException(xml.dom.NOT_FOUND_ERR) |
paulb@72 | 398 | if hasattr(tmp, "as_native_node"): |
paulb@218 | 399 | return self.impl.get_node(Node_replaceChild(self._node, tmp.as_native_node(), oldNode.as_native_node()), self) |
paulb@18 | 400 | else: |
paulb@218 | 401 | return self.impl.get_node(Node_replaceChild(self._node, tmp, oldNode.as_native_node()), self) |
paulb@18 | 402 | |
paulb@18 | 403 | def appendChild(self, tmp): |
paulb@276 | 404 | if tmp.ownerDocument != self.ownerDocument: |
paulb@276 | 405 | raise xml.dom.DOMException(xml.dom.WRONG_DOCUMENT_ERR) |
paulb@72 | 406 | if hasattr(tmp, "as_native_node"): |
paulb@218 | 407 | return self.impl.get_node(Node_appendChild(self._node, tmp.as_native_node()), self) |
paulb@18 | 408 | else: |
paulb@218 | 409 | return self.impl.get_node(Node_appendChild(self._node, tmp), self) |
paulb@18 | 410 | |
paulb@18 | 411 | def removeChild(self, tmp): |
paulb@72 | 412 | if hasattr(tmp, "as_native_node"): |
paulb@72 | 413 | Node_removeChild(self._node, tmp.as_native_node()) |
paulb@72 | 414 | else: |
paulb@72 | 415 | Node_removeChild(self._node, tmp) |
paulb@276 | 416 | return tmp |
paulb@18 | 417 | |
paulb@262 | 418 | def getElementById(self, identifier): |
paulb@262 | 419 | nodes = self.xpath(".//*[@xml:id='" + identifier.replace("'", "'") + "']", |
paulb@262 | 420 | namespaces={"xml" : xml.dom.XML_NAMESPACE}) |
paulb@262 | 421 | if nodes: |
paulb@262 | 422 | return nodes[0] |
paulb@262 | 423 | else: |
paulb@262 | 424 | return None |
paulb@262 | 425 | |
paulb@99 | 426 | def getElementsByTagName(self, tagName): |
paulb@232 | 427 | return self.xpath(".//" + tagName) |
paulb@99 | 428 | |
paulb@99 | 429 | def getElementsByTagNameNS(self, namespaceURI, localName): |
paulb@232 | 430 | return self.xpath(".//ns:" + localName, namespaces={"ns" : namespaceURI}) |
paulb@99 | 431 | |
paulb@124 | 432 | def normalize(self): |
paulb@124 | 433 | text_nodes = [] |
paulb@124 | 434 | for node in self.childNodes: |
paulb@124 | 435 | if node.nodeType == node.TEXT_NODE: |
paulb@124 | 436 | text_nodes.append(node) |
paulb@124 | 437 | elif len(text_nodes) != 0: |
paulb@124 | 438 | self._normalize(text_nodes) |
paulb@124 | 439 | text_nodes = [] |
paulb@124 | 440 | if len(text_nodes) != 0: |
paulb@124 | 441 | self._normalize(text_nodes) |
paulb@124 | 442 | |
paulb@124 | 443 | def _normalize(self, text_nodes): |
paulb@124 | 444 | texts = [] |
paulb@124 | 445 | for text_node in text_nodes[:-1]: |
paulb@124 | 446 | texts.append(text_node.nodeValue) |
paulb@124 | 447 | self.removeChild(text_node) |
paulb@124 | 448 | texts.append(text_nodes[-1].nodeValue) |
paulb@124 | 449 | self.replaceChild(self.ownerDocument.createTextNode("".join(texts)), text_nodes[-1]) |
paulb@124 | 450 | |
paulb@18 | 451 | childNodes = property(_childNodes) |
paulb@276 | 452 | firstChild = property(_firstChild) |
paulb@276 | 453 | lastChild = property(_lastChild) |
paulb@86 | 454 | value = data = nodeValue = property(_nodeValue, _setNodeValue) |
paulb@236 | 455 | textContent = property(_textContent) |
paulb@18 | 456 | name = nodeName = property(_nodeName) |
paulb@18 | 457 | tagName = property(_tagName) |
paulb@18 | 458 | namespaceURI = property(_namespaceURI) |
paulb@18 | 459 | prefix = property(_prefix) |
paulb@18 | 460 | localName = property(_localName) |
paulb@88 | 461 | parentNode = property(_parentNode) |
paulb@18 | 462 | nodeType = property(_nodeType) |
paulb@18 | 463 | attributes = property(_attributes) |
paulb@24 | 464 | previousSibling = property(_previousSibling) |
paulb@18 | 465 | nextSibling = property(_nextSibling) |
paulb@154 | 466 | doctype = property(_doctype) |
paulb@154 | 467 | publicId = property(_publicId) |
paulb@154 | 468 | systemId = property(_systemId) |
paulb@154 | 469 | |
paulb@154 | 470 | # NOTE: To be fixed - these being doctype-specific values. |
paulb@154 | 471 | |
paulb@154 | 472 | entities = {} |
paulb@154 | 473 | notations = {} |
paulb@18 | 474 | |
paulb@240 | 475 | def isSameNode(self, other): |
paulb@240 | 476 | return self == other |
paulb@18 | 477 | |
paulb@262 | 478 | def __hash__(self): |
paulb@262 | 479 | return hash(self.localName) |
paulb@262 | 480 | |
paulb@240 | 481 | def __eq__(self, other): |
paulb@276 | 482 | return isinstance(other, Node) and Node_equals(self._node, other._node) |
paulb@240 | 483 | |
paulb@240 | 484 | def __ne__(self, other): |
paulb@240 | 485 | return not (self == other) |
paulb@18 | 486 | |
paulb@32 | 487 | # 4DOM extensions to the usual PyXML API. |
paulb@32 | 488 | # NOTE: To be finished. |
paulb@32 | 489 | |
paulb@32 | 490 | def xpath(self, expr, variables=None, namespaces=None): |
paulb@324 | 491 | |
paulb@324 | 492 | """ |
paulb@324 | 493 | Evaluate the given expression 'expr' using the optional 'variables' and |
paulb@324 | 494 | 'namespaces' mappings. |
paulb@324 | 495 | """ |
paulb@324 | 496 | |
paulb@301 | 497 | ns = {} |
paulb@301 | 498 | ns.update(default_ns) |
paulb@301 | 499 | ns.update(namespaces or {}) |
paulb@301 | 500 | result = Node_xpath(self._node, expr, variables, ns) |
paulb@202 | 501 | if isinstance(result, str): |
paulb@202 | 502 | return to_unicode(result) |
paulb@202 | 503 | elif hasattr(result, "__len__"): |
paulb@218 | 504 | return NodeList([self.impl.get_node(_node, self) for _node in result]) |
paulb@81 | 505 | else: |
paulb@81 | 506 | return result |
paulb@81 | 507 | |
paulb@324 | 508 | # Other extensions to the usual PyXML API. |
paulb@324 | 509 | |
paulb@324 | 510 | def xinclude(self): |
paulb@324 | 511 | |
paulb@324 | 512 | """ |
paulb@324 | 513 | Process XInclude declarations within the document, returning the number |
paulb@324 | 514 | of substitutions performed (zero or more), raising an XIncludeException |
paulb@324 | 515 | otherwise. |
paulb@324 | 516 | """ |
paulb@324 | 517 | |
paulb@324 | 518 | return Node_xinclude(self._node) |
paulb@324 | 519 | |
paulb@81 | 520 | # Convenience methods. |
paulb@81 | 521 | |
paulb@120 | 522 | def toString(self, encoding=None, prettyprint=0): |
paulb@120 | 523 | return toString(self, encoding, prettyprint) |
paulb@81 | 524 | |
paulb@120 | 525 | def toStream(self, stream, encoding=None, prettyprint=0): |
paulb@120 | 526 | toStream(self, stream, encoding, prettyprint) |
paulb@81 | 527 | |
paulb@120 | 528 | def toFile(self, f, encoding=None, prettyprint=0): |
paulb@120 | 529 | toFile(self, f, encoding, prettyprint) |
paulb@75 | 530 | |
paulb@88 | 531 | # Attribute nodes. |
paulb@88 | 532 | |
paulb@88 | 533 | class Attribute(Node): |
paulb@88 | 534 | |
paulb@88 | 535 | "A class providing attribute access." |
paulb@88 | 536 | |
paulb@218 | 537 | def __init__(self, node, impl, ownerDocument=None, ownerElement=None): |
paulb@218 | 538 | Node.__init__(self, node, impl, ownerDocument) |
paulb@88 | 539 | self.ownerElement = ownerElement |
paulb@88 | 540 | |
paulb@88 | 541 | def _parentNode(self): |
paulb@88 | 542 | return self.ownerElement |
paulb@88 | 543 | |
paulb@88 | 544 | parentNode = property(_parentNode) |
paulb@88 | 545 | |
paulb@75 | 546 | # Document housekeeping mechanisms. |
paulb@75 | 547 | |
paulb@258 | 548 | class _Document: |
paulb@75 | 549 | |
paulb@258 | 550 | """ |
paulb@258 | 551 | An abstract class providing document-level housekeeping and distinct |
paulb@258 | 552 | functionality. |
paulb@258 | 553 | """ |
paulb@75 | 554 | |
paulb@218 | 555 | def __init__(self, node, impl): |
paulb@75 | 556 | self._node = node |
paulb@256 | 557 | self.implementation = self.impl = impl |
paulb@256 | 558 | |
paulb@256 | 559 | def _documentElement(self): |
paulb@256 | 560 | return self.xpath("*")[0] |
paulb@75 | 561 | |
paulb@75 | 562 | def _ownerDocument(self): |
paulb@188 | 563 | return self |
paulb@75 | 564 | |
paulb@75 | 565 | def __del__(self): |
paulb@84 | 566 | #print "Freeing document", self._node |
paulb@75 | 567 | libxml2mod.xmlFreeDoc(self._node) |
paulb@75 | 568 | |
paulb@256 | 569 | documentElement = property(_documentElement) |
paulb@75 | 570 | ownerDocument = property(_ownerDocument) |
paulb@154 | 571 | |
paulb@258 | 572 | class Document(_Document, Node): |
paulb@258 | 573 | |
paulb@258 | 574 | """ |
paulb@258 | 575 | A generic document class. Specialised document classes should inherit from |
paulb@258 | 576 | the _Document class and their own variation of Node. |
paulb@258 | 577 | """ |
paulb@258 | 578 | |
paulb@258 | 579 | pass |
paulb@258 | 580 | |
paulb@154 | 581 | class DocumentType(object): |
paulb@154 | 582 | |
paulb@154 | 583 | "A class providing a container for document type information." |
paulb@154 | 584 | |
paulb@154 | 585 | def __init__(self, localName, publicId, systemId): |
paulb@154 | 586 | self.name = self.localName = localName |
paulb@154 | 587 | self.publicId = publicId |
paulb@154 | 588 | self.systemId = systemId |
paulb@154 | 589 | |
paulb@154 | 590 | # NOTE: Nothing is currently provided to support the following |
paulb@154 | 591 | # NOTE: attributes. |
paulb@154 | 592 | |
paulb@154 | 593 | self.entities = {} |
paulb@154 | 594 | self.notations = {} |
paulb@32 | 595 | |
paulb@223 | 596 | # Constants. |
paulb@223 | 597 | |
paulb@223 | 598 | null_value_node_types = [ |
paulb@223 | 599 | Node.DOCUMENT_NODE, Node.DOCUMENT_TYPE_NODE, Node.ELEMENT_NODE, |
paulb@223 | 600 | Node.ENTITY_NODE, Node.ENTITY_REFERENCE_NODE, Node.NOTATION_NODE |
paulb@223 | 601 | ] |
paulb@223 | 602 | |
paulb@18 | 603 | # Utility functions. |
paulb@18 | 604 | |
paulb@18 | 605 | def createDocumentType(localName, publicId, systemId): |
paulb@223 | 606 | return default_impl.createDocumentType(localName, publicId, systemId) |
paulb@18 | 607 | |
paulb@18 | 608 | def createDocument(namespaceURI, localName, doctype): |
paulb@223 | 609 | return default_impl.createDocument(namespaceURI, localName, doctype) |
paulb@18 | 610 | |
paulb@268 | 611 | def parse(stream_or_string, html=0, htmlencoding=None, unfinished=0, impl=None): |
paulb@105 | 612 | |
paulb@105 | 613 | """ |
paulb@105 | 614 | Parse the given 'stream_or_string', where the supplied object can either be |
paulb@136 | 615 | a stream (such as a file or stream object), or a string (containing the |
paulb@268 | 616 | filename of a document). The optional parameters described below should be |
paulb@268 | 617 | provided as keyword arguments. |
paulb@268 | 618 | |
paulb@268 | 619 | If the optional 'html' parameter is set to a true value, the content to be |
paulb@268 | 620 | parsed will be treated as being HTML rather than XML. If the optional |
paulb@268 | 621 | 'htmlencoding' is specified, HTML parsing will be performed with the |
paulb@268 | 622 | document encoding assumed to that specified. |
paulb@268 | 623 | |
paulb@268 | 624 | If the optional 'unfinished' parameter is set to a true value, unfinished |
paulb@268 | 625 | documents will be parsed, even though such documents may be missing content |
paulb@268 | 626 | such as closing tags. |
paulb@105 | 627 | |
paulb@105 | 628 | A document object is returned by this function. |
paulb@105 | 629 | """ |
paulb@105 | 630 | |
paulb@218 | 631 | impl = impl or default_impl |
paulb@218 | 632 | |
paulb@18 | 633 | if hasattr(stream_or_string, "read"): |
paulb@18 | 634 | stream = stream_or_string |
paulb@268 | 635 | return parseString(stream.read(), html=html, htmlencoding=htmlencoding, unfinished=unfinished, impl=impl) |
paulb@18 | 636 | else: |
paulb@268 | 637 | return parseFile(stream_or_string, html=html, htmlencoding=htmlencoding, unfinished=unfinished, impl=impl) |
paulb@32 | 638 | |
paulb@268 | 639 | def parseFile(filename, html=0, htmlencoding=None, unfinished=0, impl=None): |
paulb@105 | 640 | |
paulb@105 | 641 | """ |
paulb@268 | 642 | Parse the file having the given 'filename'. The optional parameters |
paulb@268 | 643 | described below should be provided as keyword arguments. |
paulb@268 | 644 | |
paulb@268 | 645 | If the optional 'html' parameter is set to a true value, the content to be |
paulb@268 | 646 | parsed will be treated as being HTML rather than XML. If the optional |
paulb@268 | 647 | 'htmlencoding' is specified, HTML parsing will be performed with the |
paulb@268 | 648 | document encoding assumed to that specified. |
paulb@268 | 649 | |
paulb@268 | 650 | If the optional 'unfinished' parameter is set to a true value, unfinished |
paulb@268 | 651 | documents will be parsed, even though such documents may be missing content |
paulb@268 | 652 | such as closing tags. |
paulb@105 | 653 | |
paulb@105 | 654 | A document object is returned by this function. |
paulb@105 | 655 | """ |
paulb@105 | 656 | |
paulb@218 | 657 | impl = impl or default_impl |
paulb@268 | 658 | return impl.adoptDocument(Node_parseFile(filename, html=html, htmlencoding=htmlencoding, unfinished=unfinished)) |
paulb@18 | 659 | |
paulb@268 | 660 | def parseString(s, html=0, htmlencoding=None, unfinished=0, impl=None): |
paulb@105 | 661 | |
paulb@105 | 662 | """ |
paulb@268 | 663 | Parse the content of the given string 's'. The optional parameters described |
paulb@268 | 664 | below should be provided as keyword arguments. |
paulb@268 | 665 | |
paulb@268 | 666 | If the optional 'html' parameter is set to a true value, the content to be |
paulb@268 | 667 | parsed will be treated as being HTML rather than XML. If the optional |
paulb@268 | 668 | 'htmlencoding' is specified, HTML parsing will be performed with the |
paulb@268 | 669 | document encoding assumed to that specified. |
paulb@268 | 670 | |
paulb@268 | 671 | If the optional 'unfinished' parameter is set to a true value, unfinished |
paulb@268 | 672 | documents will be parsed, even though such documents may be missing content |
paulb@268 | 673 | such as closing tags. |
paulb@105 | 674 | |
paulb@105 | 675 | A document object is returned by this function. |
paulb@105 | 676 | """ |
paulb@105 | 677 | |
paulb@218 | 678 | impl = impl or default_impl |
paulb@268 | 679 | return impl.adoptDocument(Node_parseString(s, html=html, htmlencoding=htmlencoding, unfinished=unfinished)) |
paulb@18 | 680 | |
paulb@268 | 681 | def parseURI(uri, html=0, htmlencoding=None, unfinished=0, impl=None): |
paulb@105 | 682 | |
paulb@105 | 683 | """ |
paulb@268 | 684 | Parse the content found at the given 'uri'. The optional parameters |
paulb@268 | 685 | described below should be provided as keyword arguments. |
paulb@268 | 686 | |
paulb@268 | 687 | If the optional 'html' parameter is set to a true value, the content to be |
paulb@268 | 688 | parsed will be treated as being HTML rather than XML. If the optional |
paulb@268 | 689 | 'htmlencoding' is specified, HTML parsing will be performed with the |
paulb@268 | 690 | document encoding assumed to that specified. |
paulb@268 | 691 | |
paulb@268 | 692 | If the optional 'unfinished' parameter is set to a true value, unfinished |
paulb@268 | 693 | documents will be parsed, even though such documents may be missing content |
paulb@268 | 694 | such as closing tags. |
paulb@128 | 695 | |
paulb@232 | 696 | XML documents are retrieved using libxml2's own network capabilities; HTML |
paulb@232 | 697 | documents are retrieved using the urllib module provided by Python. To |
paulb@232 | 698 | retrieve either kind of document using Python's own modules for this purpose |
paulb@232 | 699 | (such as urllib), open a stream and pass it to the parse function: |
paulb@128 | 700 | |
paulb@232 | 701 | f = urllib.urlopen(uri) |
paulb@232 | 702 | try: |
paulb@232 | 703 | doc = libxml2dom.parse(f, html) |
paulb@232 | 704 | finally: |
paulb@232 | 705 | f.close() |
paulb@105 | 706 | |
paulb@105 | 707 | A document object is returned by this function. |
paulb@105 | 708 | """ |
paulb@105 | 709 | |
paulb@232 | 710 | if html: |
paulb@232 | 711 | f = urllib.urlopen(uri) |
paulb@232 | 712 | try: |
paulb@268 | 713 | return parse(f, html=html, htmlencoding=htmlencoding, unfinished=unfinished, impl=impl) |
paulb@232 | 714 | finally: |
paulb@232 | 715 | f.close() |
paulb@232 | 716 | else: |
paulb@232 | 717 | impl = impl or default_impl |
paulb@268 | 718 | return impl.adoptDocument(Node_parseURI(uri, html=html, htmlencoding=htmlencoding, unfinished=unfinished)) |
paulb@18 | 719 | |
paulb@120 | 720 | def toString(node, encoding=None, prettyprint=0): |
paulb@105 | 721 | |
paulb@105 | 722 | """ |
paulb@105 | 723 | Return a string containing the serialised form of the given 'node' and its |
paulb@105 | 724 | children. The optional 'encoding' can be used to override the default |
paulb@120 | 725 | character encoding used in the serialisation. The optional 'prettyprint' |
paulb@120 | 726 | indicates whether the serialised form is prettyprinted or not (the default |
paulb@120 | 727 | setting). |
paulb@105 | 728 | """ |
paulb@105 | 729 | |
paulb@120 | 730 | return Node_toString(node.as_native_node(), encoding, prettyprint) |
paulb@18 | 731 | |
paulb@120 | 732 | def toStream(node, stream, encoding=None, prettyprint=0): |
paulb@105 | 733 | |
paulb@105 | 734 | """ |
paulb@105 | 735 | Write the serialised form of the given 'node' and its children to the given |
paulb@105 | 736 | 'stream'. The optional 'encoding' can be used to override the default |
paulb@120 | 737 | character encoding used in the serialisation. The optional 'prettyprint' |
paulb@120 | 738 | indicates whether the serialised form is prettyprinted or not (the default |
paulb@120 | 739 | setting). |
paulb@105 | 740 | """ |
paulb@105 | 741 | |
paulb@120 | 742 | Node_toStream(node.as_native_node(), stream, encoding, prettyprint) |
paulb@72 | 743 | |
paulb@120 | 744 | def toFile(node, filename, encoding=None, prettyprint=0): |
paulb@105 | 745 | |
paulb@105 | 746 | """ |
paulb@105 | 747 | Write the serialised form of the given 'node' and its children to a file |
paulb@105 | 748 | having the given 'filename'. The optional 'encoding' can be used to override |
paulb@120 | 749 | the default character encoding used in the serialisation. The optional |
paulb@120 | 750 | 'prettyprint' indicates whether the serialised form is prettyprinted or not |
paulb@120 | 751 | (the default setting). |
paulb@105 | 752 | """ |
paulb@105 | 753 | |
paulb@120 | 754 | Node_toFile(node.as_native_node(), filename, encoding, prettyprint) |
paulb@18 | 755 | |
paulb@218 | 756 | def adoptNodes(nodes, impl=None): |
paulb@105 | 757 | |
paulb@105 | 758 | """ |
paulb@105 | 759 | A special utility method which adopts the given low-level 'nodes' and which |
paulb@105 | 760 | returns a list of high-level equivalents. This is currently experimental and |
paulb@105 | 761 | should not be casually used. |
paulb@105 | 762 | """ |
paulb@105 | 763 | |
paulb@218 | 764 | impl = impl or default_impl |
paulb@218 | 765 | |
paulb@81 | 766 | if len(nodes) == 0: |
paulb@81 | 767 | return [] |
paulb@236 | 768 | doc = impl.adoptDocument(libxml2mod.doc(nodes[0])) |
paulb@81 | 769 | results = [] |
paulb@81 | 770 | for node in nodes: |
paulb@218 | 771 | results.append(Node(node, impl, doc)) |
paulb@81 | 772 | return results |
paulb@81 | 773 | |
paulb@240 | 774 | def getDOMImplementation(): |
paulb@240 | 775 | |
paulb@240 | 776 | "Return the default DOM implementation." |
paulb@240 | 777 | |
paulb@240 | 778 | return default_impl |
paulb@240 | 779 | |
paulb@218 | 780 | # Single instance of the implementation. |
paulb@218 | 781 | |
paulb@218 | 782 | default_impl = Implementation() |
paulb@218 | 783 | |
paulb@18 | 784 | # vim: tabstop=4 expandtab shiftwidth=4 |