Ejemplo n.º 1
0
def builtin():
    '''Run the builtin tests from the C14N spec.'''
    for i in range(len(examples)):
        num = i + 1
        eg = examples[i]

        filename = 'out%d.xml' % num
        try:
            os.unlink(filename)
        except:
            pass

        print 'Doing %d, %s...' % (num, string.replace(eg[0:30], '\n', '\\n')),

        r = ReaderforC14NExamples()
        try:
            dom = r.fromString(eg)
        except Exception, e:
            print '\nException', repr(e)
            traceback.print_exc()
            continue

        # Get the nodeset; the tests have some special cases.
        pattern = '(//. | //@* | //namespace::*)'
        con = Context(dom)
        if eg == eg5:
            pattern = '(//. | //@* | //namespace::*)[not (self::comment())]'
        elif eg == eg7:
            con = Context(dom, processorNss={'ietf': 'http://www.ietf.org'})

        nodelist = xpath.Evaluate(pattern, context=con)

        s = StringIO.StringIO()
        outf = utf8_writer(s)

        #Get the unsuppressedPrefixes for exc-c14n; the tests have special casese
        pfxlist = []

        # Canonicalize a DOM with a document subset list according to XML-C14N
        if eg == eg1:
            Canonicalize(dom, outf, subset=nodelist, comments=1)
        else:
            Canonicalize(dom, outf, subset=nodelist)

        expected = base64.decodestring(test_results[eg])
        if s.getvalue() == expected:
            print 'Ok'
        else:
            print 'Error!'
            print 'Got:\n', s.getvalue()
            print 'Expected:\n', expected
Ejemplo n.º 2
0
def evaluateXPath(content, xpath):

    # Variables necesarias para establecer el espacio de nombres de un
    # contexto para consultas XPath
    UML_PREFIX = "UML"
    UML_URL = "org.omg.xmi.namespace.UML"

    # Establezco el contenido como contexto para las consultas XPath
    context = Context(content)
    context.setNamespaces({UML_PREFIX: UML_URL})

    # Creo la consulta XPath
    expresion = Compile(xpath)

    # Devuelve evaluacion de la consulta XPath
    return expresion.evaluate(context)
Ejemplo n.º 3
0
 def get_num_elements(self, name):
     '''
     An API function to get the number of elements for a variable.
     Do not use this function to build loops, Use iterator instead.
     '''
     context = Context(self.current_node, processorNss=self.namespaces)
     results_list = Evaluate(name, context=context)
     return len(results_list)
Ejemplo n.º 4
0
 def xpath(self, expression, other_namespaces=None):
     if other_namespaces:
         other_namespaces = other_namespaces.copy()
         other_namespaces.update(_MATH_NS_DICT)
     else:
         other_namespaces = _MATH_NS_DICT
     context = Context(self, processorNss=other_namespaces)
     return xpath.Evaluate(expression, context=context)
Ejemplo n.º 5
0
 def iterator(self, name):
     '''
     An iterator over the values of a certain name.
     The iterator changes state of interenal variables and objects.
     When calling get_value in a loop, this will result each time in a different value.
     '''
     saved_node = self.current_node
     context = Context(self.current_node, processorNss=self.namespaces)
     results_list = Evaluate(name, context=context)
     for node in results_list:
         self.current_node = node
         yield node
     self.current_node = saved_node
Ejemplo n.º 6
0
 def xpath(self, expression, other_namespaces=None):
     """Evaluate an XPath expression against the MathDOM.  The
     'math' prefix will automatically be available for the
     MathML namespace.  If other namespaces are needed, the can
     be specified as a {prefix : namespaceURI} dictionary.
     """
     if other_namespaces:
         other_namespaces = other_namespaces.copy()
         other_namespaces.update(_MATH_NS_DICT)
     else:
         other_namespaces = _MATH_NS_DICT
     context = Context(self._document.documentElement,
                       processorNss=other_namespaces)
     return xpath.Evaluate(expression, context=context)
Ejemplo n.º 7
0
    def get_value(self, name, display_type='value'):
        '''
        The API function for quering the translator for values of a certain variable.
        Called in a loop will result in a different value each time.

        @param name: the name of the variable you want the value of
        @param display_type: an optional value for the type of the desired output, one of: value, tag, ind1, ind2, code, fulltag;
               These can be easily added in the proper place of the code (display_value)
        '''
        context = Context(self.current_node, processorNss=self.namespaces)
        results_list = Evaluate(name, context=context)
        if len(results_list) == 0:
            return ''
        # Select text node value of selected nodes
        # and concatenate
        return ' '.join([node.childNodes[0].nodeValue.encode( "utf-8" )
                for node in results_list])
Ejemplo n.º 8
0
            else:
                import codecs
                encoding, filename = arg.split(',')
                reader = codecs.lookup(encoding)[2]
                IN = reader(open(filename, 'r'))
        elif opt in ('-o', '--out'):
            if arg.find(',') == -1:
                OUT = open(arg, 'w')
            else:
                import codecs
                encoding, filename = arg.split(',')
                writer = codecs.lookup(encoding)[3]
                OUT = writer(open(filename, 'w'))
        elif opt in ('-x', '--xpath'):
            query = arg

    r = PYE()
    dom = r.fromStream(IN)
    context = Context(dom, processorNss=nsdict)
    nodelist = xpath.Evaluate(query, context=context)
    if exclusive:
        Canonicalize(dom,
                     OUT,
                     subset=nodelist,
                     comments=comments,
                     unsuppressedPrefixes=pfxlist)
    else:
        Canonicalize(dom, OUT, subset=nodelist,
                     comments=comments)  #    nsdict=nsdict
    OUT.close()