Python lxml.etree 模块,RelaxNG() 实例源码

我们从Python开源项目中,提取了以下5个代码示例,用于说明如何使用lxml.etree.RelaxNG()

项目:qmlutil    作者:NVSeismoLab    | 项目源码 | 文件源码
def validate(f, schema="BED"):
    """
    Validate a QuakeML file using a given RelaxNG schema
    """
    from lxml import etree

    # Load schema
    schemafile = VALIDATION_SCHEMAS[schema]
    schema = etree.parse(schemafile)
    rng = etree.RelaxNG(schema)

    # Load QuakeML
    if isinstance(f, file):
        qml = etree.parse(f)
    elif isinstance(f, unicode):
        qml = etree.fromstring(f.encode())
    elif isinstance(f, str):
        qml = etree.fromstring(f)

    is_valid = rng.validate(qml)
    return is_valid
项目:lgr-core    作者:icann    | 项目源码 | 文件源码
def validate_document(self, rng_schema_path):
        # Construct the RelaxNG validator
        schema = etree.RelaxNG(file=rng_schema_path)

        # Parse the XML file
        parser = etree.XMLParser(**self.PARSER_OPTIONS)
        doc = etree.parse(self.source, parser=parser)

        logger.debug("Validating document '%s' with RNG '%s'",
                     self.source, rng_schema_path)

        error_log = None
        if not schema.validate(doc):
            logger.warning("Validation of document '%s' failed",
                           self.source)
            error_log = schema.error_log
            if len(error_log) == 0:
                # Bug in LXML, see https://bugs.launchpad.net/lxml/+bug/1526522
                error_log = "CANNOT VALIDATE XML"

        return error_log
项目:py-openmath    作者:OpenMath    | 项目源码 | 文件源码
def normative_validator():
    """ Load the normative validator provided by the OpenMath foundation. """

    relaxng_doc = etree.parse(resource_filename(__name__, 'openmath2.rng'))
    return etree.RelaxNG(relaxng_doc)
项目:health-mosconi    作者:GNUHealth-Mosconi    | 项目源码 | 文件源码
def test_view(self):
        'Test validity of all views of the module'
        with Transaction().start(DB_NAME, USER,
                context=CONTEXT) as transaction:
            View = POOL.get('ir.ui.view')
            views = View.search([
                    ('module', '=', self.module),
                    ('model', '!=', ''),
                    ])
            for view in views:
                if view.inherit and view.inherit.model == view.model:
                    view_id = view.inherit.id
                else:
                    view_id = view.id
                model = view.model
                Model = POOL.get(model)
                res = Model.fields_view_get(view_id)
                assert res['model'] == model
                tree = etree.fromstring(res['arch'])

                validator = etree.RelaxNG(etree=View.get_rng(res['type']))
                validator.assert_(tree)

                tree_root = tree.getroottree().getroot()

                for element in tree_root.iter():
                    if element.tag in ('field', 'label', 'separator', 'group'):
                        for attr in ('name', 'icon'):
                            field = element.get(attr)
                            if field:
                                assert field in res['fields'], (
                                    'Missing field: %s' % field)
            transaction.cursor.rollback()
项目:health-mosconi    作者:GNUHealth-Mosconi    | 项目源码 | 文件源码
def check_xml(cls, views):
        "Check XML"
        for view in views:
            if not view.arch:
                continue
            xml = view.arch.strip()
            if not xml:
                continue
            tree = etree.fromstring(xml)

            if hasattr(etree, 'RelaxNG'):
                rng_type = view.inherit.type if view.inherit else view.type
                validator = etree.RelaxNG(etree=cls.get_rng(rng_type))
                if not validator.validate(tree):
                    error_log = reduce(lambda x, y: str(x) + '\n' + str(y),
                            validator.error_log.filter_from_errors())
                    logger.error('Invalid xml view:\n%s',
                        str(error_log) + '\n' + xml)
                    cls.raise_user_error('invalid_xml', (view.rec_name,))
            root_element = tree.getroottree().getroot()

            # validate pyson attributes
            validates = {
                'states': fields.states_validate,
            }

            def encode(element):
                for attr in ('states', 'domain', 'spell'):
                    if element.get(attr):
                        try:
                            value = PYSONDecoder().decode(element.get(attr))
                            validates.get(attr, lambda a: True)(value)
                        except Exception, e:
                            logger.error('Invalid pyson view element "%s:%s":'
                                '\n%s\n%s',
                                element.get('id') or element.get('name'), attr,
                                str(e), xml)
                            return False
                for child in element:
                    if not encode(child):
                        return False
                return True
            if not encode(root_element):
                cls.raise_user_error('invalid_xml', (view.rec_name,))