Example #1
0
 def _initializeSheet(self, rootNode):
     if rootNode.namespaceURI == XSL_NAMESPACE:
         if rootNode.localName in ['stylesheet', 'transform']:
             if not rootNode.getAttributeNS(EMPTY_NAMESPACE, 'version'):
                 raise XsltException(Error.STYLESHEET_MISSING_VERSION)
             #rootNode.__dict__['extensionNss'] = []
         else:
             raise XsltException(Error.STYLESHEET_ILLEGAL_ROOT, rootNode.nodeName)
     else:
         vattr = rootNode.getAttributeNodeNS(XSL_NAMESPACE, 'version')
         if not vattr:
             root_nss = GetAllNs(rootNode)
             if filter(lambda x, n=root_nss: n[x] == XSL_NAMESPACE, root_nss.keys()):
                 raise XsltException(Error.STYLESHEET_MISSING_VERSION)
             else:
                 raise XsltException(Error.STYLESHEET_MISSING_VERSION_NOTE1)
         sheet = StylesheetElement(self._ownerDoc, XSL_NAMESPACE,
                                   'transform', vattr.prefix,
                                   self._ssheetUri)
         sheet.setAttributeNS(EMPTY_NAMESPACE, 'version', vattr.value)
         tpl = TemplateElement(self._ownerDoc, XSL_NAMESPACE, 'template',
                               vattr.prefix, self._ssheetUri)
         tpl.setAttributeNS(EMPTY_NAMESPACE, 'match', '/')
         sheet.appendChild(tpl)
         sheet.__dict__['extensionNss'] = []
         self._nodeStack[-1].appendChild(sheet)
         # Ensure the literal element is a child of the template
         # endElement appends to the end of the nodeStack
         self._nodeStack.append(tpl)
     self._firstElement = 0
     return
Example #2
0
 def _initializeSheet(self, rootNode):
     if rootNode.namespaceURI == XSL_NAMESPACE:
         if rootNode.localName in ['stylesheet', 'transform']:
             if not rootNode.getAttributeNS(EMPTY_NAMESPACE, 'version'):
                 raise XsltException(Error.STYLESHEET_MISSING_VERSION)
             #rootNode.__dict__['extensionNss'] = []
         else:
             raise XsltException(Error.STYLESHEET_ILLEGAL_ROOT,
                                 rootNode.nodeName)
     else:
         vattr = rootNode.getAttributeNodeNS(XSL_NAMESPACE, 'version')
         if not vattr:
             root_nss = GetAllNs(rootNode)
             if filter(lambda x, n=root_nss: n[x] == XSL_NAMESPACE,
                       root_nss.keys()):
                 raise XsltException(Error.STYLESHEET_MISSING_VERSION)
             else:
                 raise XsltException(Error.STYLESHEET_MISSING_VERSION_NOTE1)
         sheet = StylesheetElement(self._ownerDoc, XSL_NAMESPACE,
                                   'transform', vattr.prefix,
                                   self._ssheetUri)
         sheet.setAttributeNS(EMPTY_NAMESPACE, 'version', vattr.value)
         tpl = TemplateElement(self._ownerDoc, XSL_NAMESPACE, 'template',
                               vattr.prefix, self._ssheetUri)
         tpl.setAttributeNS(EMPTY_NAMESPACE, 'match', '/')
         sheet.appendChild(tpl)
         sheet.__dict__['extensionNss'] = []
         self._nodeStack[-1].appendChild(sheet)
         # Ensure the literal element is a child of the template
         # endElement appends to the end of the nodeStack
         self._nodeStack.append(tpl)
     self._firstElement = 0
     return
Example #3
0
 def select(self, context, nodeTest):
     """Select all of the namespaces from the context"""
     if context.node.nodeType != Node.ELEMENT_NODE:
         return ([], 0)
     result = []
     #nss = context.nss()
     nss = GetAllNs(context.node)
     for prefix in nss.keys():
         nsNode = NamespaceNode.NamespaceNode(
             prefix, nss[prefix],
             (context.node.ownerDocument or context.node))
         if nodeTest(context, nsNode, self.principalType):
             result.append(nsNode)
     return (result, 0)
 def select(self, context, nodeTest):
     """Select all of the namespaces from the context"""
     if context.node.nodeType != Node.ELEMENT_NODE:
         return ([], 0)
     result = []
     #nss = context.nss()
     nss = GetAllNs(context.node)
     for prefix in nss.keys():
         nsNode = NamespaceNode.NamespaceNode(
             prefix, nss[prefix],
             (context.node.ownerDocument or context.node)
             )
         if nodeTest(context, nsNode, self.principalType):
             result.append(nsNode)
     return (result, 0)
 def xpath(self, expr=''):
     """ Return the snippets corresponding to the given xpath query.
                 
     """
     from xml.dom.ext import GetAllNs
     from xml import xpath
     
     dom = self.get_dom(self(method='xml'))
     context = xpath.Context.Context(dom,
                                     processorNss=GetAllNs(dom.documentElement))
     return xpath.Evaluate(expr, context=context)
Example #6
0
    def startElement(self, name, attribs):
        self._completeTextNode()
        (name, qname, nsattribs) = self._handleStartElementNss(name, attribs)
        nsuri = name[0]
        local = name[1]
        prefix = SplitQName(qname)[0]
        mapping = g_mappings.get(nsuri, None)
        del_extu = []
        if mapping:
            if not mapping.has_key(local):
                if self._firstElement:
                    raise XsltException(Error.STYLESHEET_ILLEGAL_ROOT, name)
                else:
                    raise XsltException(Error.XSLT_ILLEGAL_ELEMENT, local)
            xsl_class = mapping[local]
            if xsl_class == IncludeElement:
                #Can the included sheet have literal result element as root?
                inc = self.clone().fromUri(nsattribs[('', 'href')],
                                           baseUri=self._ssheetUri,
                                           ownerDoc=self._ownerDoc)
                sty = inc.firstChild
                included_nss = GetAllNs(sty)
                for child in sty.childNodes[:]:
                    self._nodeStack[-1].appendChild(child)
                    #migrate old nss from stylesheet directly to new child
                    for prefix in included_nss.keys():
                        if prefix:
                            child.setAttributeNS(XMLNS_NAMESPACE,
                                                 'xmlns:'+prefix,
                                                 included_nss[prefix])
                        else:
                            child.setAttributeNS(XMLNS_NAMESPACE, 'xmlns',
                                                 included_nss[prefix])
                self._nodeStack.append(None)
                pDomlette.ReleaseNode(inc)
                return
            else:
                xsl_instance = xsl_class(self._ownerDoc,
                                         baseUri=self._ssheetUri)
            for aqname in nsattribs.getQNames():
                (ansuri, alocal) = nsattribs.getNameByQName(aqname)


                value = nsattribs.getValueByQName(aqname)
                if ansuri != XMLNS_NAMESPACE and xsl_class == StylesheetElement:
                    self._handleExtUris(ansuri, alocal, value, '',
                                        del_extu,xsl_instance)
                elif not ansuri and alocal not in xsl_instance.__class__.legalAttrs:
                    raise XsltException(Error.XSLT_ILLEGAL_ATTR,
                                        aqname, xsl_instance.nodeName)

                xsl_instance.setAttributeNS(ansuri, aqname, value)
        else:
            if nsuri in self._extUris and self._extElements:
                #Default XsltElement behavior effects fallback
                ext_class = self._extElements.get((nsuri, local), XsltElement)
                xsl_instance = ext_class(self._ownerDoc, nsuri, local,
                                         prefix, self._ssheetUri)
            else:
                xsl_instance = LiteralElement(self._ownerDoc, nsuri, local,
                                              prefix, self._ssheetUri)
            for aqname in nsattribs.getQNames():
                (ansuri, alocal) = nsattribs.getNameByQName(aqname)
                value = nsattribs.getValueByQName(aqname)
                if ansuri != XMLNS_NAMESPACE:
                    self._handleExtUris(ansuri, alocal, value, '',
                                        del_extu, xsl_instance)
                    if hasattr(xsl_instance.__class__, 'legalAttrs'):
                        if not ansuri and alocal not in xsl_instance.__class__.legalAttrs:
                            raise XsltException(Error.XSLT_ILLEGAL_ATTR,
                                                alocal, xsl_instance.nodeName)
                xsl_instance.setAttributeNS(ansuri, aqname, value)
        self._extUriStack.append(del_extu)
        if (xsl_instance.namespaceURI, xsl_instance.localName) == (XSL_NAMESPACE, 'text') or xsl_instance.getAttributeNS(XML_NAMESPACE, 'space') == 'preserve':
            self._preserveStateStack.append(1)
        elif xsl_instance.getAttributeNS(XML_NAMESPACE, 'space') == 'default':
            self._preserveStateStack.append(0)
        else:
            self._preserveStateStack.append(self._preserveStateStack[-1])
        if self._firstElement:
            self._initializeSheet(xsl_instance)
        self._nodeStack.append(xsl_instance)
        return
Example #7
0
def FromDocument(oldDoc, baseUri='',stylesheetReader = None):
    #FIXME: We really shouldn't mutate the given doc, but this is the easiest way to strip whitespace
    if baseUri and baseUri[-1] == '/':
        modBaseUri = baseUri
    else:
        modBaseUri = baseUri + '/'
    oldDoc.normalize()
    extElements = xslt.g_extElements
    source_root = oldDoc.documentElement
    #Set up a new document for the stylesheet nodes
    if source_root.namespaceURI == XSL_NAMESPACE:
        if source_root.localName not in ['stylesheet', 'transform']:
            raise XsltException(Error.STYLESHEET_ILLEGAL_ROOT, source_root.nodeName)
        result_elem_root = 0
    else:
        result_elem_root = 1
    xsl_doc = createDocument()
    ext_uris = []
    if result_elem_root:
        vattr = source_root.getAttributeNodeNS(XSL_NAMESPACE, 'version')
        if not vattr:
            root_nss = GetAllNs(source_root)
            if filter(lambda x, n=root_nss: n[x] == XSL_NAMESPACE, root_nss.keys()):
                raise XsltException(Error.STYLESHEET_MISSING_VERSION)
            else:
                raise XsltException(Error.STYLESHEET_MISSING_VERSION_NOTE1)

        sheet = StylesheetElement(xsl_doc, XSL_NAMESPACE,
                                  'transform', vattr.prefix,
                                  baseUri)
        sheet.setAttributeNS(EMPTY_NAMESPACE, 'version', vattr.value)
        tpl = TemplateElement(xsl_doc, XSL_NAMESPACE, 'template',
                              vattr.prefix, baseUri)

        tpl.setAttributeNS(EMPTY_NAMESPACE, 'match', '/')
        sheet.appendChild(tpl)
        sheet.__dict__['extensionNss'] = []
        xsl_doc.appendChild(sheet)
        DomConvert(source_root, tpl, xsl_doc, [], extElements, 0)
    else:
        sheet = StylesheetElement(xsl_doc, source_root.prefix, source_root.localName, baseUri=baseUri)
        sty_nss = GetAllNs(source_root)
        for attr in source_root.attributes.values():
            if (attr.namespaceURI, attr.localName) == ('', 'extension-element-prefixes'):
                ext_prefixes = string.splitfields(attr.value)
                for prefix in ext_prefixes:
                    if prefix == '#default': prefix = ''
                    ext_uris.append(sty_nss[prefix])
            sheet.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value)
        sheet.__dict__['extensionNss'] = ext_uris
        if not sheet.getAttributeNS(EMPTY_NAMESPACE, 'version'):
            raise XsltException(Error.STYLESHEET_MISSING_VERSION)
        xsl_doc.appendChild(sheet)
        for child in source_root.childNodes:
            DomConvert(child, sheet, xsl_doc, ext_uris, extElements, 0)
    #Handle includes
    includes = filter(lambda x: x.nodeType == Node.ELEMENT_NODE and (x.namespaceURI, x.localName) == (XSL_NAMESPACE, 'include'), sheet.childNodes)
    for inc in includes:
        href = inc.getAttributeNS(EMPTY_NAMESPACE,'href')
        if stylesheetReader is None:
            stylesheetReader = StylesheetReader()
        docfrag = stylesheetReader.fromUri(href,baseUri = baseUri, ownerDoc=xsl_doc)
        sty = docfrag.firstChild
        included_nss = GetAllNs(sty)
        for child in sty.childNodes[:]:
            if child.nodeType != Node.ELEMENT_NODE:
                continue
            sheet.insertBefore(child, inc)
            #migrate old nss from stylesheet directly to new child
            for prefix in included_nss.keys():
                if prefix:
                    child.setAttributeNS(XMLNS_NAMESPACE, 'xmlns:'+prefix,
                                                 included_nss[prefix])
                else:
                    child.setAttributeNS(XMLNS_NAMESPACE, 'xmlns',
                                         included_nss[prefix])

        sheet.removeChild(inc)
        ReleaseNode(inc)
        #sty.reclaim()
    try:
        sheet.setup()
    except:
        ReleaseNode(sheet.ownerDocument)
        raise
    return sheet
Example #8
0
    def startElement(self, name, attribs):
        self._completeTextNode()
        (name, qname, nsattribs) = self._handleStartElementNss(name, attribs)
        nsuri = name[0]
        local = name[1]
        prefix = SplitQName(qname)[0]
        mapping = g_mappings.get(nsuri, None)
        del_extu = []
        if mapping:
            if not mapping.has_key(local):
                if self._firstElement:
                    raise XsltException(Error.STYLESHEET_ILLEGAL_ROOT, name)
                else:
                    raise XsltException(Error.XSLT_ILLEGAL_ELEMENT, local)
            xsl_class = mapping[local]
            if xsl_class == IncludeElement:
                #Can the included sheet have literal result element as root?
                inc = self.clone().fromUri(nsattribs[('', 'href')],
                                           baseUri=self._ssheetUri,
                                           ownerDoc=self._ownerDoc)
                sty = inc.firstChild
                included_nss = GetAllNs(sty)
                for child in sty.childNodes[:]:
                    self._nodeStack[-1].appendChild(child)
                    #migrate old nss from stylesheet directly to new child
                    for prefix in included_nss.keys():
                        if prefix:
                            child.setAttributeNS(XMLNS_NAMESPACE,
                                                 'xmlns:' + prefix,
                                                 included_nss[prefix])
                        else:
                            child.setAttributeNS(XMLNS_NAMESPACE, 'xmlns',
                                                 included_nss[prefix])
                self._nodeStack.append(None)
                pDomlette.ReleaseNode(inc)
                return
            else:
                xsl_instance = xsl_class(self._ownerDoc,
                                         baseUri=self._ssheetUri)
            for aqname in nsattribs.getQNames():
                (ansuri, alocal) = nsattribs.getNameByQName(aqname)

                value = nsattribs.getValueByQName(aqname)
                if ansuri != XMLNS_NAMESPACE and xsl_class == StylesheetElement:
                    self._handleExtUris(ansuri, alocal, value, '', del_extu,
                                        xsl_instance)
                elif not ansuri and alocal not in xsl_instance.__class__.legalAttrs:
                    raise XsltException(Error.XSLT_ILLEGAL_ATTR, aqname,
                                        xsl_instance.nodeName)

                xsl_instance.setAttributeNS(ansuri, aqname, value)
        else:
            if nsuri in self._extUris and self._extElements:
                #Default XsltElement behavior effects fallback
                ext_class = self._extElements.get((nsuri, local), XsltElement)
                xsl_instance = ext_class(self._ownerDoc, nsuri, local, prefix,
                                         self._ssheetUri)
            else:
                xsl_instance = LiteralElement(self._ownerDoc, nsuri, local,
                                              prefix, self._ssheetUri)
            for aqname in nsattribs.getQNames():
                (ansuri, alocal) = nsattribs.getNameByQName(aqname)
                value = nsattribs.getValueByQName(aqname)
                if ansuri != XMLNS_NAMESPACE:
                    self._handleExtUris(ansuri, alocal, value, '', del_extu,
                                        xsl_instance)
                    if hasattr(xsl_instance.__class__, 'legalAttrs'):
                        if not ansuri and alocal not in xsl_instance.__class__.legalAttrs:
                            raise XsltException(Error.XSLT_ILLEGAL_ATTR,
                                                alocal, xsl_instance.nodeName)
                xsl_instance.setAttributeNS(ansuri, aqname, value)
        self._extUriStack.append(del_extu)
        if (xsl_instance.namespaceURI, xsl_instance.localName) == (
                XSL_NAMESPACE, 'text') or xsl_instance.getAttributeNS(
                    XML_NAMESPACE, 'space') == 'preserve':
            self._preserveStateStack.append(1)
        elif xsl_instance.getAttributeNS(XML_NAMESPACE, 'space') == 'default':
            self._preserveStateStack.append(0)
        else:
            self._preserveStateStack.append(self._preserveStateStack[-1])
        if self._firstElement:
            self._initializeSheet(xsl_instance)
        self._nodeStack.append(xsl_instance)
        return
Example #9
0
def DomConvert(node, xslParent, xslDoc, extUris, extElements, preserveSpace):
    if node.nodeType == Node.ELEMENT_NODE:
        mapping = g_mappings.get(node.namespaceURI, None)
        if mapping:
            if not mapping.has_key(node.localName):
                raise XsltException(Error.XSLT_ILLEGAL_ELEMENT, node.localName)
            xsl_class = mapping[node.localName]

            xsl_instance = xsl_class(xslDoc, baseUri=xslParent.baseUri)
            for attr in node.attributes.values():
                if not attr.namespaceURI and attr.localName not in xsl_instance.__class__.legalAttrs:
                    raise XsltException(Error.XSLT_ILLEGAL_ATTR, attr.nodeName,
                                        xsl_instance.nodeName)
                xsl_instance.setAttributeNS(attr.namespaceURI, attr.nodeName,
                                            attr.value)
            xslParent.appendChild(xsl_instance)
        elif node.namespaceURI in extUris:
            name = (node.namespaceURI, node.localName)
            if name in extElements.keys():
                ext_class = extElements[name]
            else:
                #Default XsltElement behavior effects fallback
                ext_class = XsltElement
            xsl_instance = ext_class(xslDoc, node.namespaceURI, node.localName,
                                     node.prefix, xslParent.baseUri)
            for attr in node.attributes.values():
                if (attr.namespaceURI,
                        attr.localName) == (XSL_NAMESPACE,
                                            'extension-element-prefixes'):
                    ext_prefixes = string.splitfields(attr.value)
                    for prefix in ext_prefixes:
                        if prefix == '#default': prefix = ''
                        extUris.append(node_nss[prefix])
                xsl_instance.setAttributeNS(attr.namespaceURI, attr.nodeName,
                                            attr.value)
            xslParent.appendChild(xsl_instance)
        else:
            xsl_instance = LiteralElement(xslDoc, node.namespaceURI,
                                          node.localName, node.prefix,
                                          xslParent.baseUri)
            node_nss = GetAllNs(node)
            for attr in node.attributes.values():
                if (attr.namespaceURI,
                        attr.localName) == (XSL_NAMESPACE,
                                            'extension-element-prefixes'):
                    ext_prefixes = string.splitfields(attr.value)
                    for prefix in ext_prefixes:
                        if prefix == '#default': prefix = ''
                        extUris.append(node_nss[prefix])
                xsl_instance.setAttributeNS(attr.namespaceURI, attr.nodeName,
                                            attr.value)
            xslParent.appendChild(xsl_instance)
        ps = (xsl_instance.namespaceURI, xsl_instance.localName) == (
            XSL_NAMESPACE, 'text') or xsl_instance.getAttributeNS(
                XML_NAMESPACE, 'space') == 'preserve'
        #ps = (xsl_instance.namespaceURI, xsl_instance.localName) == (XSL_NAMESPACE, 'text')
        for child in node.childNodes:
            DomConvert(child, xsl_instance, xslDoc, extUris, extElements, ps)
    elif node.nodeType == Node.TEXT_NODE:
        if string.strip(node.data) or preserveSpace:
            xsl_instance = LiteralText(xslDoc, node.data)
            xslParent.appendChild(xsl_instance)
    return
Example #10
0
def FromDocument(oldDoc, baseUri='', stylesheetReader=None):
    #FIXME: We really shouldn't mutate the given doc, but this is the easiest way to strip whitespace
    if baseUri and baseUri[-1] == '/':
        modBaseUri = baseUri
    else:
        modBaseUri = baseUri + '/'
    oldDoc.normalize()
    extElements = xslt.g_extElements
    source_root = oldDoc.documentElement
    #Set up a new document for the stylesheet nodes
    if source_root.namespaceURI == XSL_NAMESPACE:
        if source_root.localName not in ['stylesheet', 'transform']:
            raise XsltException(Error.STYLESHEET_ILLEGAL_ROOT,
                                source_root.nodeName)
        result_elem_root = 0
    else:
        result_elem_root = 1
    xsl_doc = createDocument()
    ext_uris = []
    if result_elem_root:
        vattr = source_root.getAttributeNodeNS(XSL_NAMESPACE, 'version')
        if not vattr:
            root_nss = GetAllNs(source_root)
            if filter(lambda x, n=root_nss: n[x] == XSL_NAMESPACE,
                      root_nss.keys()):
                raise XsltException(Error.STYLESHEET_MISSING_VERSION)
            else:
                raise XsltException(Error.STYLESHEET_MISSING_VERSION_NOTE1)

        sheet = StylesheetElement(xsl_doc, XSL_NAMESPACE, 'transform',
                                  vattr.prefix, baseUri)
        sheet.setAttributeNS(EMPTY_NAMESPACE, 'version', vattr.value)
        tpl = TemplateElement(xsl_doc, XSL_NAMESPACE, 'template', vattr.prefix,
                              baseUri)

        tpl.setAttributeNS(EMPTY_NAMESPACE, 'match', '/')
        sheet.appendChild(tpl)
        sheet.__dict__['extensionNss'] = []
        xsl_doc.appendChild(sheet)
        DomConvert(source_root, tpl, xsl_doc, [], extElements, 0)
    else:
        sheet = StylesheetElement(xsl_doc,
                                  source_root.prefix,
                                  source_root.localName,
                                  baseUri=baseUri)
        sty_nss = GetAllNs(source_root)
        for attr in source_root.attributes.values():
            if (attr.namespaceURI,
                    attr.localName) == ('', 'extension-element-prefixes'):
                ext_prefixes = string.splitfields(attr.value)
                for prefix in ext_prefixes:
                    if prefix == '#default': prefix = ''
                    ext_uris.append(sty_nss[prefix])
            sheet.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value)
        sheet.__dict__['extensionNss'] = ext_uris
        if not sheet.getAttributeNS(EMPTY_NAMESPACE, 'version'):
            raise XsltException(Error.STYLESHEET_MISSING_VERSION)
        xsl_doc.appendChild(sheet)
        for child in source_root.childNodes:
            DomConvert(child, sheet, xsl_doc, ext_uris, extElements, 0)
    #Handle includes
    includes = filter(
        lambda x: x.nodeType == Node.ELEMENT_NODE and
        (x.namespaceURI, x.localName) == (XSL_NAMESPACE, 'include'),
        sheet.childNodes)
    for inc in includes:
        href = inc.getAttributeNS(EMPTY_NAMESPACE, 'href')
        if stylesheetReader is None:
            stylesheetReader = StylesheetReader()
        docfrag = stylesheetReader.fromUri(href,
                                           baseUri=baseUri,
                                           ownerDoc=xsl_doc)
        sty = docfrag.firstChild
        included_nss = GetAllNs(sty)
        for child in sty.childNodes[:]:
            if child.nodeType != Node.ELEMENT_NODE:
                continue
            sheet.insertBefore(child, inc)
            #migrate old nss from stylesheet directly to new child
            for prefix in included_nss.keys():
                if prefix:
                    child.setAttributeNS(XMLNS_NAMESPACE, 'xmlns:' + prefix,
                                         included_nss[prefix])
                else:
                    child.setAttributeNS(XMLNS_NAMESPACE, 'xmlns',
                                         included_nss[prefix])

        sheet.removeChild(inc)
        ReleaseNode(inc)
        #sty.reclaim()
    try:
        sheet.setup()
    except:
        ReleaseNode(sheet.ownerDocument)
        raise
    return sheet