xmlifMinidom.py
Go to the documentation of this file.
00001 #
00002 # genxmlif, Release 0.9.0
00003 # file: xmlifMinidom.py
00004 #
00005 # XML interface class to Python standard minidom
00006 #
00007 # history:
00008 # 2005-04-25 rl   created
00009 # 2007-07-02 rl   complete re-design, internal wrapper 
00010 #                 for DOM trees and elements introduced
00011 # 2008-07-01 rl   Limited support of XInclude added
00012 #
00013 # Copyright (c) 2005-2008 by Roland Leuthe.  All rights reserved.
00014 #
00015 # --------------------------------------------------------------------
00016 # The generix XML interface is
00017 #
00018 # Copyright (c) 2005-2008 by Roland Leuthe
00019 #
00020 # By obtaining, using, and/or copying this software and/or its
00021 # associated documentation, you agree that you have read, understood,
00022 # and will comply with the following terms and conditions:
00023 #
00024 # Permission to use, copy, modify, and distribute this software and
00025 # its associated documentation for any purpose and without fee is
00026 # hereby granted, provided that the above copyright notice appears in
00027 # all copies, and that both that copyright notice and this permission
00028 # notice appear in supporting documentation, and that the name of
00029 # the author not be used in advertising or publicity
00030 # pertaining to distribution of the software without specific, written
00031 # prior permission.
00032 #
00033 # THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
00034 # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
00035 # ABILITY AND FITNESS.  IN NO EVENT SHALL THE AUTHOR
00036 # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
00037 # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
00038 # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
00039 # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
00040 # OF THIS SOFTWARE.
00041 # --------------------------------------------------------------------
00042 
00043 import string
00044 import urllib
00045 from xml.dom              import Node, XMLNS_NAMESPACE
00046 from xml.dom.expatbuilder import ExpatBuilderNS
00047 from xml.parsers.expat    import ExpatError
00048 from ..genxmlif             import XMLIF_MINIDOM, GenXmlIfError
00049 from xmlifUtils           import convertToAbsUrl, NsNameTupleFactory
00050 from xmlifDom             import XmlInterfaceDom, InternalDomTreeWrapper, InternalDomElementWrapper, XmlIfBuilderExtensionDom
00051 
00052 
00053 class XmlInterfaceMinidom (XmlInterfaceDom):
00054     """Derived interface class for handling of minidom parser.
00055     
00056     For description of the interface methods see xmlifbase.py.
00057     """
00058 
00059     def __init__ (self, verbose, useCaching, processXInclude):
00060         XmlInterfaceDom.__init__ (self, verbose, useCaching, processXInclude)
00061         self.xmlIfType = XMLIF_MINIDOM
00062         if self.verbose:
00063             print "Using minidom interface module..."
00064 
00065 
00066     def createXmlTree (self, namespace, xmlRootTagName, attributeDict={}, publicId=None, systemId=None):
00067         from xml.dom.minidom import getDOMImplementation
00068         domImpl = getDOMImplementation()
00069         doctype = domImpl.createDocumentType(xmlRootTagName, publicId, systemId)
00070         domTree = domImpl.createDocument(namespace, xmlRootTagName, doctype)
00071         treeWrapper = self.treeWrapperClass(self, InternalMinidomTreeWrapper(domTree), self.useCaching)
00072 
00073         intRootNodeWrapper = InternalMinidomElementWrapper(domTree.documentElement, treeWrapper.getTree())
00074         rootNodeWrapper = self.elementWrapperClass (intRootNodeWrapper, treeWrapper, []) # TODO: namespace handling
00075         for attrName, attrValue in attributeDict.items():
00076             rootNodeWrapper.setAttribute (attrName, attrValue)
00077 
00078         return treeWrapper
00079 
00080 
00081     def parse (self, file, baseUrl="", internalOwnerDoc=None):
00082         absUrl = convertToAbsUrl(file, baseUrl)
00083         fp     = urllib.urlopen (absUrl)
00084         try:
00085             builder = ExtExpatBuilderNS(file, absUrl, self)
00086             tree = builder.parseFile(fp)
00087 
00088             # XInclude support
00089             if self.processXInclude:
00090                 if internalOwnerDoc == None: 
00091                     internalOwnerDoc = builder.treeWrapper.getTree()
00092                 self.xInclude (builder.treeWrapper.getRootNode(), absUrl, internalOwnerDoc)
00093 
00094             fp.close()
00095         except ExpatError, errInst:
00096             fp.close()
00097             raise GenXmlIfError, "%s: ExpatError: %s" %(file, str(errInst))
00098 
00099         return builder.treeWrapper
00100 
00101 
00102     def parseString (self, text, baseUrl="", internalOwnerDoc=None):
00103         absUrl = convertToAbsUrl ("", baseUrl)
00104         try:
00105             builder = ExtExpatBuilderNS("", absUrl, self)
00106             builder.parseString (text)
00107 
00108             # XInclude support
00109             if self.processXInclude:
00110                 if internalOwnerDoc == None: 
00111                     internalOwnerDoc = builder.treeWrapper.getTree()
00112                 self.xInclude (builder.treeWrapper.getRootNode(), absUrl, internalOwnerDoc)
00113         except ExpatError, errInst:
00114             raise GenXmlIfError, "%s: ExpatError: %s" %(baseUrl, str(errInst))
00115 
00116         return builder.treeWrapper
00117 
00118 
00119 
00120 class InternalMinidomTreeWrapper (InternalDomTreeWrapper):
00121     """Internal wrapper for a minidom Document class.
00122     """
00123     
00124     def __init__ (self, document):
00125         InternalDomTreeWrapper.__init__(self, document)
00126         self.internalElementWrapperClass = InternalMinidomElementWrapper
00127 
00128 
00129 
00130 class InternalMinidomElementWrapper (InternalDomElementWrapper):
00131     """Internal Wrapper for a Dom Element class.
00132     """
00133 
00134     def xmlIfExtGetAttributeDict (self):
00135         """Return a dictionary with all attributes of this element."""
00136         attribDict = {}
00137         for attrNameNS, attrNodeOrValue in self.element.attributes.itemsNS():
00138             attribDict[NsNameTupleFactory(attrNameNS)] = attrNodeOrValue
00139                 
00140         return attribDict
00141 
00142 
00143 
00144 class ExtExpatBuilderNS (ExpatBuilderNS, XmlIfBuilderExtensionDom):
00145     """Extended Expat Builder class derived from ExpatBuilderNS.
00146     
00147     Extended to store related line numbers, file/URL names and 
00148     defined namespaces in the node object.
00149     """
00150 
00151     def __init__ (self, filePath, absUrl, xmlIf):
00152         ExpatBuilderNS.__init__(self)
00153         internalMinidomTreeWrapper = InternalMinidomTreeWrapper(self.document)
00154         self.treeWrapper = xmlIf.treeWrapperClass(self, internalMinidomTreeWrapper, xmlIf.useCaching)
00155         XmlIfBuilderExtensionDom.__init__(self, filePath, absUrl, self.treeWrapper, xmlIf.elementWrapperClass)
00156 
00157         # set EndNamespaceDeclHandler, currently not used by minidom
00158         self.getParser().EndNamespaceDeclHandler = self.end_namespace_decl_handler
00159         self.curNamespaces = []
00160 
00161 
00162     def start_element_handler(self, name, attributes):
00163         ExpatBuilderNS.start_element_handler(self, name, attributes)
00164 
00165         # use attribute format {namespace}localName
00166         attrList = []
00167         for i in range (0, len(attributes), 2):
00168             attrName = attributes[i]
00169             attrNameSplit = string.split(attrName, " ")
00170             if len(attrNameSplit) > 1:
00171                 attrName = (attrNameSplit[0], attrNameSplit[1])
00172             attrList.extend([attrName, attributes[i+1]])
00173         
00174         internalMinidomElementWrapper = InternalMinidomElementWrapper(self.curNode, self.treeWrapper.getTree())
00175         XmlIfBuilderExtensionDom.startElementHandler (self, internalMinidomElementWrapper, self.getParser().ErrorLineNumber, self.curNamespaces[:], attrList)
00176 
00177         if self.curNode.parentNode.nodeType == Node.DOCUMENT_NODE:
00178             for namespace in self.curNamespaces:
00179                 if namespace[0] != None:
00180                     internalMinidomElementWrapper.xmlIfExtElementWrapper.attributeSequence.append((XMLNS_NAMESPACE, namespace[0]))
00181                 else:
00182                     internalMinidomElementWrapper.xmlIfExtElementWrapper.attributeSequence.append("xmlns")
00183 #                internalMinidomElementWrapper.xmlIfExtElementWrapper.setAttribute((XMLNS_NAMESPACE, namespace[0]), namespace[1])
00184 
00185 
00186     def end_element_handler(self, name):
00187         XmlIfBuilderExtensionDom.endElementHandler (self, self.curNode.xmlIfExtInternalWrapper, self.getParser().ErrorLineNumber)
00188         ExpatBuilderNS.end_element_handler(self, name)
00189 
00190 
00191     def start_namespace_decl_handler(self, prefix, uri):
00192         ExpatBuilderNS.start_namespace_decl_handler(self, prefix, uri)
00193         self.curNamespaces.insert(0, (prefix, uri))
00194 
00195 
00196     def end_namespace_decl_handler(self, prefix):
00197         assert self.curNamespaces.pop(0)[0] == prefix, "implementation confused"
00198 


mavlink
Author(s): Lorenz Meier
autogenerated on Thu Jun 6 2019 19:01:57