paulb@1 | 1 | #!/usr/bin/env python |
paulb@1 | 2 | |
paulb@1 | 3 | """ |
paulb@1 | 4 | DOM wrapper around libxml2. |
paulb@1 | 5 | """ |
paulb@1 | 6 | |
paulb@1 | 7 | import xml.dom |
paulb@1 | 8 | |
paulb@1 | 9 | class Attribute(object): |
paulb@1 | 10 | |
paulb@1 | 11 | def __init__(self, node): |
paulb@1 | 12 | self._node = node |
paulb@1 | 13 | |
paulb@1 | 14 | class Node(object): |
paulb@1 | 15 | |
paulb@1 | 16 | _nodeTypes = { |
paulb@1 | 17 | "attribute" : xml.dom.Node.ATTRIBUTE_NODE, |
paulb@1 | 18 | "comment" : xml.dom.Node.COMMENT_NODE, |
paulb@1 | 19 | "document_xml" : xml.dom.Node.DOCUMENT_NODE, |
paulb@1 | 20 | "doctype" : xml.dom.Node.DOCUMENT_TYPE_NODE, |
paulb@1 | 21 | "element" : xml.dom.Node.ELEMENT_NODE, |
paulb@1 | 22 | "entity" : xml.dom.Node.ENTITY_NODE, |
paulb@1 | 23 | "entity_ref" : xml.dom.Node.ENTITY_REFERENCE_NODE, |
paulb@1 | 24 | "notation" : xml.dom.Node.NOTATION_NODE, |
paulb@1 | 25 | "pi" : xml.dom.Node.PROCESSING_INSTRUCTION_NODE, |
paulb@1 | 26 | "text" : xml.dom.Node.TEXT_NODE |
paulb@1 | 27 | } |
paulb@1 | 28 | |
paulb@1 | 29 | def __init__(self, node): |
paulb@1 | 30 | self._node = node |
paulb@1 | 31 | |
paulb@1 | 32 | def _ownerDocument(self): |
paulb@1 | 33 | return self._node.doc |
paulb@1 | 34 | |
paulb@1 | 35 | def _nodeType(self): |
paulb@1 | 36 | return self._nodeTypes[self._node.type] |
paulb@1 | 37 | |
paulb@1 | 38 | def _childNodes(self): |
paulb@1 | 39 | child_nodes = [] |
paulb@1 | 40 | child_node = self._node.children |
paulb@1 | 41 | while child_node is not None: |
paulb@1 | 42 | child_nodes.append( |
paulb@1 | 43 | self.__class__(child_node)) |
paulb@1 | 44 | child_node = child_node.next |
paulb@1 | 45 | return child_nodes |
paulb@1 | 46 | |
paulb@1 | 47 | def _attributes(self): |
paulb@1 | 48 | attributes = [] |
paulb@1 | 49 | attribute = self._node.properties |
paulb@1 | 50 | while attribute is not None: |
paulb@1 | 51 | attributes.append( |
paulb@1 | 52 | Attribute(attribute)) |
paulb@1 | 53 | attribute = attribute.next |
paulb@1 | 54 | return attributes |
paulb@1 | 55 | |
paulb@1 | 56 | def _tagName(self): |
paulb@1 | 57 | if self._node.type == "element": |
paulb@1 | 58 | return self._node.name |
paulb@1 | 59 | else: |
paulb@1 | 60 | return None |
paulb@1 | 61 | |
paulb@1 | 62 | def _namespaceURI(self): |
paulb@1 | 63 | if self._node.type == "element": |
paulb@1 | 64 | return self._node.ns().content |
paulb@1 | 65 | else: |
paulb@1 | 66 | return None |
paulb@1 | 67 | |
paulb@1 | 68 | nodeType = property(_nodeType) |
paulb@1 | 69 | ownerDocument = property(_ownerDocument) |
paulb@1 | 70 | childNodes = property(_childNodes) |
paulb@1 | 71 | attributes = property(_attributes) |
paulb@1 | 72 | tagName = property(_tagName) |
paulb@1 | 73 | namespaceURI = property(_namespaceURI) |
paulb@1 | 74 | |
paulb@1 | 75 | # vim: tabstop=4 expandtab shiftwidth=4 |