def validate(self, schema): """ Validate the XML in *file_* against a given schema. | *Parameters:* | *schema*........path to the schema file (*must* be RelaxNG) | *Return:* | True if schema validates successfully, False otherwise """ try: from lxml import etree from lxml.etree import RelaxNG except ImportError: raise Exception( '[XMLObject.validate] Need lxml to validate xml!') try: relaxng_doc = etree.parse(schema) relaxng = RelaxNG(relaxng_doc) xml_doc = etree.parse(self._file) except etree.XMLSyntaxError as e: raise Exception( '[XMLObject.validate] Cannot validate xml: ' + str(e)) return relaxng.validate(xml_doc)
def validate(self, schema): """ Validate the XML in *file_* against a given schema. | *Parameters:* | *schema*........path to the schema file (*must* be RelaxNG) | *Return:* | True if schema validates successfully, False otherwise """ try: from lxml import etree from lxml.etree import RelaxNG except ImportError: raise Exception('[XMLObject.validate] Need lxml to validate xml!') try: relaxng_doc = etree.parse(schema) relaxng = RelaxNG(relaxng_doc) xml_doc = etree.parse(self._file) except etree.XMLSyntaxError as e: raise Exception('[XMLObject.validate] Cannot validate xml: ' + str(e)) return relaxng.validate(xml_doc)
def validate_admin(xml): """ Validate a document agains admin.rng. Parameters and exceptions are the same as in L{enkel.exml.validate.validate_inline}. """ rng_file = join(RNGDIR, "admin.rng") rng_doc = parse(rng_file) rng = RelaxNG(rng_doc) rng.assertValid(xml)
def validate_post(xml): """ Validate a post. Validate a xml document against section.rng. Parameters and excetions are the same as L{enkel.exml.validate.validate_inline}. """ rng_doc = parse(rng_file) rng = RelaxNG(rng_doc) rng.assertValid(xml)
def validate3(fieldname, xml, offset): rng = RelaxNG(XML(""" <element name='b' xmlns='http://relaxng.org/ns/structure/1.0'> <text/> </element>""")) try: rng.assertValid(XML(xml)) except LxmlError, e: raise LxmlFieldValidationError(fieldname, xml, offset, e)
def validate(self, xml_tree): if self._start is None: rng_tree = self._tree else: rng_tree = self._relocate_xslt(self._tree, newref="'%s'" % self._start) # ugly hack to get around namespace (?) issues rng_tree = parse(StringIO(str(rng_tree))) rng = RelaxNG(rng_tree) self.validate = rng.validate # replace the object method by the real thing return rng.validate(xml_tree)
def validate_tei(xmldoc): # , filename="" '''Check if an XML document is conform to the guidelines of the Text Encoding Initiative''' global TEI_RELAXNG if TEI_RELAXNG is None: # load validator with lzma.open(TEI_SCHEMA, 'rb') as schemafile: schema_data = load_pickle(schemafile) TEI_RELAXNG = RelaxNG(fromstring(schema_data)) result = TEI_RELAXNG.validate(xmldoc) if result is False: LOGGER.warning('not a valid TEI document: %s', TEI_RELAXNG.error_log.last_error) return result
def test_hidden_and_readonly(self): m = data.Manip(dict(x=String())) m.x = "test" form = Form("http://example.com/myform", "Submit") form["x"] = ModelData(m) form["x"].display["x"] = {"hidden": True} s = form.create() RelaxNG(parse(RNG)).assertValid(XML(s)) form["x"].display["x"] = {"readonly": True} s = form.create() RelaxNG(parse(RNG)).assertValid(XML(s))
def rng(): """ get RNG schema of CMI format """ return RelaxNG( reader( os.path.join(os.path.dirname(__file__), "standard/schema/cmi-customization.rng")))
def _test_fieldgen(self, model, value): m = data.Manip(model) m.x = value form = Form("http://example.com/myform", "Submit") form["x"] = ModelData(m) form["x"].meta["x"] = {"label": "The label"} s = form.create() self.assertEquals(s.count("The label"), 1) RelaxNG(parse(RNG)).assertValid(XML(s)) return s
def test_preprocess(self): posts = join(self.tmp, "posts") tags = join(self.tmp, "tags") preprocess(posts, tags, self.postsfolder) rng = RelaxNG(parse(join(SRNGDIR, "posts.rng"))) rng.assertValid(parse(posts)) res = open(posts, "rb").read() self.assertEquals(res.count("<post "), 3) rng = RelaxNG(parse(join(SRNGDIR, "tags.rng"))) rng.assertValid(parse(tags)) res = open(tags, "rb").read() self.assertEquals(res.count("<tag "), 3)
def _test_shema(cls): root = cls.element_schema() root.set('datatypeLibrary', 'http://www.w3.org/2001/XMLSchema-datatypes') xml = tostring(root, pretty_print=True) idx = 1 print('') for s in xml.split('\n'): print("%03d: %s" % (idx, s)) idx += 1 print('') RelaxNG(fromstring(xml))
def convert_record(filename: str, xsl_filename: str): source_doc = parse(filename) with open('epitafium.rnc') as schema_file: schema = RelaxNG.from_rnc_string(schema_file.read()) if schema.validate(source_doc): pass # print("VALID!") else: for err in schema.error_log: print(err) # Transform xslt = parse(xsl_filename) transform = XSLT(xslt) target_doc = transform(source_doc) # Output return target_doc.getroot()
def validator(request): return RelaxNG( file=os.path.join(os.path.dirname(__file__), '..', 'doc', 'sil.rng'))
def schema(cls): root = cls.element_schema() root.set('datatypeLibrary', 'http://www.w3.org/2001/XMLSchema-datatypes') return RelaxNG(fromstring(tostring(root)))
SCHEMA = RelaxNG.from_rnc_string("""# # RELAX NG schema for the RPKI Repository Delta Protocol (RRDP). # default namespace = "http://www.ripe.net/rpki/rrdp" version = xsd:positiveInteger { maxInclusive="1" } serial = xsd:positiveInteger uri = xsd:anyURI uuid = xsd:string { pattern = "[\-0-9a-fA-F]+" } hash = xsd:string { pattern = "[0-9a-fA-F]+" } base64 = xsd:base64Binary # Notification File: lists current snapshots and deltas. start |= element notification { attribute version { version }, attribute session_id { uuid }, attribute serial { serial }, element snapshot { attribute uri { uri }, attribute hash { hash } }, element delta { attribute serial { serial }, attribute uri { uri }, attribute hash { hash } }* } # Snapshot segment: think DNS AXFR. start |= element snapshot { attribute version { version }, attribute session_id { uuid }, attribute serial { serial }, element publish { attribute uri { uri }, base64 }* } # Delta segment: think DNS IXFR. start |= element delta { attribute version { version }, attribute session_id { uuid }, attribute serial { serial }, delta_element+ } delta_element |= element publish { attribute uri { uri }, attribute hash { hash }?, base64 } delta_element |= element withdraw { attribute uri { uri }, attribute hash { hash } } # Local Variables: # indent-tabs-mode: nil # comment-start: "# " # comment-start-skip: "#[ \\t]*" # End: """)
from datetime import datetime from functools import singledispatch from types import GeneratorType from typing import Any, Dict, List, Optional, Union, cast from lxml.builder import E from lxml.etree import RelaxNG, _Element NoneType = type(None) CURRENT_DIR = os.path.abspath(os.path.dirname(__file__)) TIME_FORMAT = "%Y%m%dT%H:%M:%S" TIME_FORMATS = [TIME_FORMAT, "%Y%m%dT%H%M%S"] SCHEMA = RelaxNG(file=os.path.join(CURRENT_DIR, "xmlrpc.rng")) class Binary(bytes): @classmethod def fromstring(cls, data: Optional[str]) -> "Binary": if data is None: return cls(b"") return cls(base64.b64decode(data)) XmlRpcTypes = Union[str, bytes, bool, datetime, int, Binary, NoneType, "XmlRpcArrayType", "XmlRpcStructType", ] XmlRpcArrayType = List[XmlRpcTypes] XmlRpcStructType = Dict[str, XmlRpcTypes]