当前位置: 首页>>代码示例>>Python>>正文


Python etree.DTD类代码示例

本文整理汇总了Python中lxml.etree.DTD的典型用法代码示例。如果您正苦于以下问题:Python DTD类的具体用法?Python DTD怎么用?Python DTD使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了DTD类的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: validate_norm

def validate_norm(fn, nn, version, it):
    global norm 
    global result

    # open XML parser
    n = parse(open(os.path.join(path, fn)))
    # validate DTD
    dtd = DTD(open(os.path.join(path, 'normalizer.dtd')))
    assert dtd.validate(n) == True
    # Create normalizer from xml definition
    norm = Normalizer(n, os.path.join(path, 'common_tagTypes.xml'),
                      os.path.join(path, 'common_callBacks.xml'))
    # Time normalizer validation
    try:
        assert norm.name.lower() == nn.lower()
        if norm.name != nn:
            print "Warning, %s has name attribute set to %s" % (fn, norm.name)
    except AssertionError:
        print "\n[%s]" % norm.name, "and [%s]" % nn, "don't match"
        return
    try:
        assert norm.version == version
    except AssertionError:
        print "\n[%s]" % norm.version, "and [%s]" % version, "don't match"
        return
    samples_amount = len([u for u in [v.examples for v in norm.patterns.values()]])
    if samples_amount <= 0:
        print "No samples to validate in %s" % fn
        return
    t = timeit.Timer("assert norm.validate() == True", "from __main__ import norm")
    s = t.timeit(it)
    # Normalize result against number of validated samples
    s = s / float(samples_amount)
    # Add result
    result.add_res(norm.name, norm.version, norm.authors, s)
开发者ID:Robert-McGinley,项目名称:pylogsparser,代码行数:35,代码来源:time_norm_va.py

示例2: normalize_samples

 def normalize_samples(self, norm, name, version):
     """Test logparser.normalize validate for syslog normalizer."""
     # open parser
     n = parse(open(os.path.join(self.normalizer_path, norm)))
     # validate DTD
     dtd = DTD(open(os.path.join(self.normalizer_path,
                                 'normalizer.dtd')))
     dtd.assertValid(n)
     # Create normalizer from xml definition
     normalizer = Normalizer(n, os.path.join(self.normalizer_path, 'common_tagTypes.xml'), os.path.join(self.normalizer_path, 'common_callBacks.xml'))
     self.assertEquals(normalizer.name, name)
     self.assertEquals(normalizer.version, version)
     self.assertTrue(normalizer.validate())
开发者ID:ukolka,项目名称:pylogsparser,代码行数:13,代码来源:test_normalizer.py

示例3: xhtmlValidate

def xhtmlValidate(modelXbrl, elt):
    from lxml.etree import DTD, XMLSyntaxError
    # copy xhtml elements to fresh tree
    with open(os.path.join(modelXbrl.modelManager.cntlr.configDir, "xhtml1-strict-ix.dtd")) as fh:
        dtd = DTD(fh)
    try:
        if not dtd.validate( XmlUtil.ixToXhtml(elt) ):
            modelXbrl.error("xmlDTD:error",
                _("%(element)s error %(error)s"),
                modelObject=elt, element=elt.localName.title(),
                error=', '.join(e.message for e in dtd.error_log.filter_from_errors()))
    except XMLSyntaxError as err:
        modelXbrl.error("xmlDTD:error",
            _("%(element)s error %(error)s"),
            modelObject=elt, element=elt.localName.title(), error=dtd.error_log.filter_from_errors())
开发者ID:jaolguin,项目名称:Arelle,代码行数:15,代码来源:XmlValidate.py

示例4: __init__

 def __init__(self, normalizers_path, active_normalizers={}):
     """
     Instantiates a flow manager. The default behavior is to activate every
     available normalizer.
     
     @param normalizer_path: absolute path to the normalizer XML definitions
     to use.
     @param active_normalizers: a dictionary of active normalizers
     in the form {name: [True|False]}.
     """
     self.normalizers_path = normalizers_path
     self.active_normalizers = active_normalizers
     self.dtd = DTD(open(os.path.join(self.normalizers_path, "normalizer.dtd")))
     self._cache = []
     self.reload()
开发者ID:ohe,项目名称:pylogsparser,代码行数:15,代码来源:lognormalizer.py

示例5: __init__

 def __init__(self, normalizers_paths, active_normalizers = {}):
     """
     Instantiates a flow manager. The default behavior is to activate every
     available normalizer.
     
     @param normalizers_paths: a list of absolute paths to the normalizer
     XML definitions to use or a just a single path as str.
     @param active_normalizers: a dictionary of active normalizers
     in the form {name-version : [True|False]}.
     """
     if not isinstance(normalizers_paths, list or tuple):
         normalizers_paths = [normalizers_paths,]
     self.normalizers_paths = normalizers_paths
     self.active_normalizers = active_normalizers
     self.dtd, self.ctt, self.ccb = None, None, None
     
     # Walk through paths for normalizer.dtd and common_tagTypes.xml
     # /!\ dtd file and common elements will be overrriden if present in
     # many directories.
     for norm_path in self.normalizers_paths:
         if not os.path.isdir(norm_path):
             raise ValueError, "Invalid normalizer directory : %s" % norm_path
         dtd = os.path.join(norm_path, 'normalizer.dtd')
         ctt = os.path.join(norm_path, 'common_tagTypes.xml')
         ccb = os.path.join(norm_path, 'common_callBacks.xml')
         if os.path.isfile(dtd):
             self.dtd = DTD(open(dtd))
         if os.path.isfile(ctt):
             self.ctt = ctt
         if os.path.isfile(ccb):
             self.ccb = ccb
     # Technically the common elements files should NOT be mandatory.
     # But many normalizers use them, so better safe than sorry.
     if not self.dtd or not self.ctt or not self.ccb:
         raise StandardError, "Missing DTD or common library files"
     self._cache = []
     self.reload()
开发者ID:chaydock,项目名称:pylogsparser,代码行数:37,代码来源:lognormalizer.py

示例6: __init__

 def __init__(self, normalizers_paths, active_normalizers = {}):
     """
     Instantiates a flow manager. The default behavior is to activate every
     available normalizer.
     
     @param normalizers_paths: a list of absolute paths to the normalizer
     XML definitions to use or a just a single path as str.
     @param active_normalizers: a dictionary of active normalizers
     in the form {name: [True|False]}.
     """
     if not isinstance(normalizers_paths, list or tuple):
         normalizers_paths = [normalizers_paths,]
     self.normalizers_paths = normalizers_paths
     self.active_normalizers = active_normalizers
     # Walk through paths for normalizer.dtd and common_tagTypes.xml
     for norm_path in self.normalizers_paths:
         dtd = os.path.join(norm_path, 'normalizer.dtd')
         ctt = os.path.join(norm_path, 'common_tagTypes.xml')
         if os.path.isfile(dtd):
             self.dtd = DTD(open(dtd))
         if os.path.isfile(ctt):
             self.ctt = ctt
     self._cache = []
     self.reload()
开发者ID:cnanakos,项目名称:pylogsparser,代码行数:24,代码来源:lognormalizer.py

示例7: test_00_validate_fake_syslog

 def test_00_validate_fake_syslog(self):
     """Validate the fake normalizer"""
     dtd = DTD(open(os.path.join(self.normalizer_path,
                                 'normalizer.dtd')))
     self.assertTrue(dtd.validate(self.n))
开发者ID:ukolka,项目名称:pylogsparser,代码行数:5,代码来源:test_normalizer.py

示例8: xhtmlValidate

def xhtmlValidate(modelXbrl, elt):
    from lxml.etree import DTD, XMLSyntaxError
    from arelle import FunctionIxt
    ixNsStartTags = ["{" + ns + "}" for ns in XbrlConst.ixbrlAll]
    isEFM = modelXbrl.modelManager.disclosureSystem.validationType == "EFM"
    # find ix version for messages
    _ixNS = elt.modelDocument.ixNS
    _xhtmlDTD = XHTML_DTD[_ixNS]
    _customTransforms = modelXbrl.modelManager.customTransforms or {}
    
    def checkAttribute(elt, isIxElt, attrTag, attrValue):
        ixEltAttrDefs = ixAttrDefined.get(elt.namespaceURI, EMPTYDICT).get(elt.localName, ())
        if attrTag.startswith("{"):
            ns, sep, localName = attrTag[1:].partition("}")
        else:
            ns = None
            localName = attrTag
        if ns is not None and ns not in XbrlConst.ixbrlAll and attrTag not in ixEltAttrDefs:
            if ns == XbrlConst.xsi:
                pass # xsi attributes are always allowed
            elif isIxElt:
                allowedNs = allowedNonIxAttrNS.get(elt.localName, None)
                if allowedNs != "##other" and ns != allowedNs:
                    modelXbrl.error(ixMsgCode("qualifiedAttributeNotExpected", elt),
                        _("Inline XBRL element %(element)s has qualified attribute %(name)s"),
                        modelObject=elt, element=str(elt.elementQname), name=attrTag)
                if ns == XbrlConst.xbrli and elt.localName in {
                    "fraction", "nonFraction", "nonNumeric", "references", "relationship", "tuple"}:                
                    modelXbrl.error(ixMsgCode("qualifiedAttributeDisallowed", elt),
                        _("Inline XBRL element %(element)s has disallowed attribute %(name)s"),
                        modelObject=elt, element=str(elt.elementQname), name=attrTag)
            else:
                if ns in XbrlConst.ixbrlAll:
                    modelXbrl.error(ixMsgCode("inlineAttributeMisplaced", elt, name="other"),
                        _("Inline XBRL attributes are not allowed on html elements: ix:%(name)s"),
                        modelObject=elt, name=localName)
                elif ns not in {XbrlConst.xml, XbrlConst.xsi, XbrlConst.xhtml}:
                    modelXbrl.error(ixMsgCode("extensionAttributeMisplaced", ns=_ixNS),
                        _("Extension attributes are not allowed on html elements: %(tag)s"),
                        modelObject=elt, tag=attrTag)
        elif isIxElt:
            try:
                _xsdType = ixAttrType[elt.namespaceURI][localName]
                if isinstance(_xsdType, dict):
                    baseXsdType = _xsdType["type"]
                    facets = _xsdType
                else:
                    baseXsdType = _xsdType
                    facets = None
                XmlValidate.validateValue(modelXbrl, elt, attrTag, baseXsdType, attrValue, facets=facets)
                
                if not (attrTag in ixEltAttrDefs or
                        (localName in ixEltAttrDefs and (not ns or ns in XbrlConst.ixbrlAll))):
                    raise KeyError
                disallowedXbrliAttrs = ({"scheme", "periodType",     "balance", "contextRef", "unitRef", "precision", "decimals"} -
                                        {"fraction": {"contextRef", "unitRef"},
                                         "nonFraction": {"contextRef", "unitRef", "decimals", "precision"},
                                         "nonNumeric": {"contextRef"}}.get(elt.localName, set()))
                disallowedAttrs = set(a for a in disallowedXbrliAttrs if elt.get(a) is not None)
                if disallowedAttrs:
                    modelXbrl.error(ixMsgCode("inlineElementAttributes",elt),
                        _("Inline XBRL element %(element)s has disallowed attributes %(attributes)s"),
                        modelObject=elt, element=elt.elementQname, attributes=", ".join(disallowedAttrs))
            except KeyError:
                modelXbrl.error(ixMsgCode("attributeNotExpected",elt),
                    _("Attribute %(attribute)s is not expected on element ix:%(element)s"),
                    modelObject=elt, attribute=attrTag, element=elt.localName)
        elif ns is None:
            _xsdType = htmlAttrType.get(localName)
            if _xsdType is not None:
                if isinstance(_xsdType, dict):
                    baseXsdType = _xsdType["type"]
                    facets = _xsdType
                else:
                    baseXsdType = _xsdType
                    facets = None
                XmlValidate.validateValue(modelXbrl, elt, attrTag, baseXsdType, attrValue, facets=facets)
                
    def checkHierarchyConstraints(elt):
        constraints = ixHierarchyConstraints.get(elt.localName)
        if constraints:
            for _rel, names in constraints:
                reqt = _rel[0]
                rel = _rel[1:]
                if reqt in ('&', '^', '1'):
                    nameFilter = ('*',)
                else:
                    nameFilter = names
                if nameFilter == ('*',):
                    namespaceFilter = namespacePrefix = '*'
                elif len(nameFilter) == 1 and "}" in nameFilter[0] and nameFilter[0][0] == "{":
                    namespaceFilter, _sep, nameFilter = nameFilter[0][1:].partition("}")
                    namespacePrefix = XmlUtil.xmlnsprefix(elt,namespaceFilter)
                else:
                    namespaceFilter = elt.namespaceURI
                    namespacePrefix = elt.prefix
                relations = {"ancestor": XmlUtil.ancestor, 
                             "parent": XmlUtil.parent, 
                             "child-choice": XmlUtil.children, 
                             "child-sequence": XmlUtil.children,
#.........这里部分代码省略.........
开发者ID:Arelle,项目名称:Arelle,代码行数:101,代码来源:XhtmlValidate.py

示例9: LogNormalizer

class LogNormalizer():
    """Basic normalization flow manager.
    Normalizers definitions are loaded from a path and checked against the DTD.
    If the definitions are syntactically correct, the normalizers are
    instantiated and populate the manager's cache.
    Normalization priormority is established as follows:
    
    * Maximum priority assigned to normalizers where the "appliedTo" tag is set
      to "raw". They MUST be mutually exclusive.
    * Medium priority assigned to normalizers where the "appliedTo" tag is set
      to "body".
    * Lowest priority assigned to any remaining normalizers.
    
    Some extra treatment is also done prior and after the log normalization:
    
    * Assignment of a unique ID, under the tag "uuid"
    * Conversion of date tags to UTC, if the "_timezone" was set prior to
      the normalization process."""
    
    def __init__(self, normalizers_paths, active_normalizers = {}):
        """
        Instantiates a flow manager. The default behavior is to activate every
        available normalizer.
        
        @param normalizers_paths: a list of absolute paths to the normalizer
        XML definitions to use or a just a single path as str.
        @param active_normalizers: a dictionary of active normalizers
        in the form {name: [True|False]}.
        """
        if not isinstance(normalizers_paths, list or tuple):
            normalizers_paths = [normalizers_paths,]
        self.normalizers_paths = normalizers_paths
        self.active_normalizers = active_normalizers
        # Walk through paths for normalizer.dtd and common_tagTypes.xml
        for norm_path in self.normalizers_paths:
            dtd = os.path.join(norm_path, 'normalizer.dtd')
            ctt = os.path.join(norm_path, 'common_tagTypes.xml')
            if os.path.isfile(dtd):
                self.dtd = DTD(open(dtd))
            if os.path.isfile(ctt):
                self.ctt = ctt
        self._cache = []
        self.reload()
        
    def reload(self):
        """Refreshes this instance's normalizers pool."""
        self.normalizers = { 'raw' : [], 'body' : [] }
        for path in self.iter_normalizer():
            norm = parse(open(path))
            if not self.dtd.validate(norm):
                warnings.warn('Skipping %s : invalid DTD' % path)
                print 'invalid normalizer ', path
            else:
                normalizer = Normalizer(norm, self.ctt)
                normalizer.uuid = self._compute_norm_uuid(normalizer)
                self.normalizers.setdefault(normalizer.appliedTo, [])
                self.normalizers[normalizer.appliedTo].append(normalizer)
        self.activate_normalizers()

    def _compute_norm_uuid(self, normalizer):
        return "%s-%s" % (normalizer.name, normalizer.version)

    def iter_normalizer(self):
        """ Iterates through normalizers and returns the normalizers' paths.
        
        @return: a generator of absolute paths.
        """
        for path in self.normalizers_paths:
            for root, dirs, files in os.walk(path):
                for name in files:
                    if not name.startswith('common_tagTypes') and \
                           name.endswith('.xml'):
                        yield os.path.join(root, name)

    def __len__(self):
        """ Returns the amount of available normalizers.
        """
        return len([n for n in self.iter_normalizer()])

    def update_normalizer(self, raw_xml_contents, name = None, dir_path = None ):
        """used to add or update a normalizer.
        @param raw_xml_contents: XML description of normalizer as flat XML. It
        must comply to the DTD.
        @param name: if set, the XML description will be saved as name.xml.
        If left blank, name will be fetched from the XML description.
        @param dir_path: the path to the directory where to copy the given
        normalizer.
        """
        path = self.normalizers_paths[0]
        if dir_path:
            if dir_path in self.normalizers_paths:
                path = dir_path
        xmlconf = XMLfromstring(raw_xml_contents).getroottree()
        if not self.dtd.validate(xmlconf):
            raise ValueError, "This definition file does not follow the normalizers DTD :\n\n%s" % \
                               self.dtd.error_log.filter_from_errors()
        if not name:
            name = xmlconf.getroot().get('name')
        if not name.endswith('.xml'):
            name += '.xml'
#.........这里部分代码省略.........
开发者ID:cnanakos,项目名称:pylogsparser,代码行数:101,代码来源:lognormalizer.py

示例10: template

  methods[element] = {
    'declaration': template('PCDATA_OPERATOR_DECLARATION').render(
      {'class': element, 'type': 'int'}),
    'definition': template('PCDATA_OPERATOR_DEFINITION').render(
      {'class': element, 'type': 'int'})
  }

if __name__ == '__main__':
  import argparse

  cmdline = argparse.ArgumentParser()
  cmdline.add_argument("dtd")
  cmdline.add_argument("hxx")
  cmdline.add_argument("cxx")
  args = cmdline.parse_args()
  dtd = DTD(args.dtd)
  metadata = {
    'dtd': dtd,
    'enumerations': enumerations,
    'extra_methods': methods,
    'enum_classes': sorted([(v['name'], k) for k, v in enumerations.items()
                            if not v in [e.name for e in dtd.iterelements()]]),
    'forwards_for': {'ornament': ['ornament_type'],
                     'score': ['score_data', 'score_header']}
  }
  with open(args.hxx, 'w') as hxx:
    print(template('LIBRARY_HEADER').render(metadata), file=hxx)
  with open(args.cxx, 'w') as cxx:
    print(template('LIBRARY_IMPLEMENTATION').render(metadata), file=cxx)

开发者ID:mlang,项目名称:bmmlcxx,代码行数:29,代码来源:codegen.py

示例11: xhtmlValidate

def xhtmlValidate(modelXbrl, elt):
    from lxml.etree import DTD, XMLSyntaxError
    ixNsStartTags = ["{" + ns + "}" for ns in XbrlConst.ixbrlAll]
    isEFM = modelXbrl.modelManager.disclosureSystem.validationType == "EFM"
    # find ix version for messages
    _ixNS = elt.modelDocument.ixNS
    
    def checkAttribute(elt, isIxElt, attrTag, attrValue):
        ixEltAttrDefs = ixAttrDefined.get(elt.namespaceURI, EMPTYDICT).get(elt.localName, ())
        if attrTag.startswith("{"):
            ns, sep, localName = attrTag[1:].partition("}")
        else:
            ns = None
            localName = attrTag
        if ns is not None and ns not in XbrlConst.ixbrlAll and attrTag not in ixEltAttrDefs:
            if isIxElt:
                allowedNs = allowedNonIxAttrNS.get(elt.localName, None)
                if allowedNs != "##other" and ns != allowedNs:
                    modelXbrl.error(ixMsgCode("qualifiedAttributeNotExpected", elt),
                        _("Inline XBRL element %(element)s has qualified attribute %(name)s"),
                        modelObject=elt, element=str(elt.elementQname), name=attrTag)
                if ns == XbrlConst.xbrli and elt.localName in {
                    "fraction", "nonFraction", "nonNumeric", "references", "relationship", "tuple"}:                
                    modelXbrl.error(ixMsgCode("qualifiedAttributeDisallowed", elt),
                        _("Inline XBRL element %(element)s has disallowed attribute %(name)s"),
                        modelObject=elt, element=str(elt.elementQname), name=attrTag)
            else:
                if ns in XbrlConst.ixbrlAll:
                    modelXbrl.error(ixMsgCode("inlineAttributeMisplaced", elt, name="other"),
                        _("Inline XBRL attributes are not allowed on html elements: ix:%(name)s"),
                        modelObject=elt, name=localName)
                elif ns not in {XbrlConst.xml, XbrlConst.xsi, XbrlConst.xhtml}:
                    modelXbrl.error(ixMsgCode("extensionAttributeMisplaced", ns=_ixNS),
                        _("Extension attributes are not allowed on html elements: %(tag)s"),
                        modelObject=elt, tag=attrTag)
        elif isIxElt:
            try:
                _xsdType = ixAttrType[elt.namespaceURI][localName]
                if isinstance(_xsdType, dict):
                    baseXsdType = _xsdType["type"]
                    facets = _xsdType
                else:
                    baseXsdType = _xsdType
                    facets = None
                XmlValidate.validateValue(modelXbrl, elt, attrTag, baseXsdType, attrValue, facets=facets)
                
                if not (attrTag in ixEltAttrDefs or
                        (localName in ixEltAttrDefs and (not ns or ns in XbrlConst.ixbrlAll))):
                    raise KeyError
                disallowedXbrliAttrs = ({"scheme", "periodType",     "balance", "contextRef", "unitRef", "precision", "decimals"} -
                                        {"fraction": {"contextRef", "unitRef"},
                                         "nonFraction": {"contextRef", "unitRef", "decimals", "precision"},
                                         "nonNumeric": {"contextRef"}}.get(elt.localName, set()))
                disallowedAttrs = set(a for a in disallowedXbrliAttrs if elt.get(a) is not None)
                if disallowedAttrs:
                    modelXbrl.error(ixMsgCode("inlineElementAttributes",elt),
                        _("Inline XBRL element %(element)s has disallowed attributes %(attributes)s"),
                        modelObject=elt, element=elt.elementQname, attributes=", ".join(disallowedAttrs))
            except KeyError:
                modelXbrl.error(ixMsgCode("attributeNotExpected",elt),
                    _("Attribute %(attribute)s is not expected on element ix:%(element)s"),
                    modelObject=elt, attribute=attrTag, element=elt.localName)
                
    def checkHierarchyConstraints(elt):
        constraints = ixHierarchyConstraints.get(elt.localName)
        if constraints:
            for _rel, names in constraints:
                reqt = _rel[0]
                rel = _rel[1:]
                if reqt in ('&', '^'):
                    nameFilter = ('*',)
                else:
                    nameFilter = names
                if nameFilter == ('*',):
                    namespaceFilter = namespacePrefix = '*'
                else:
                    namespaceFilter = elt.namespaceURI
                    namespacePrefix = elt.prefix
                relations = {"ancestor": XmlUtil.ancestor, 
                             "parent": XmlUtil.parent, 
                             "child-choice": XmlUtil.children, 
                             "child-sequence": XmlUtil.children,
                             "child-or-text": XmlUtil.children,
                             "descendant": XmlUtil.descendants}[rel](
                            elt, 
                            namespaceFilter,
                            nameFilter)
                if rel in ("ancestor", "parent"):
                    if relations is None: relations = []
                    else: relations = [relations]
                if rel == "child-or-text":
                    relations += XmlUtil.innerTextNodes(elt, ixExclude=True, ixEscape=False, ixContinuation=False)
                issue = ''
                if reqt == '^':
                    if not any(r.localName in names and r.namespaceURI == elt.namespaceURI
                               for r in relations):
                        issue = " and is missing one of " + ', '.join(names)
                if reqt in ('&', '^'):
                    disallowed = [str(r.elementQname)
                                  for r in relations
#.........这里部分代码省略.........
开发者ID:sagesmith-wf,项目名称:Arelle,代码行数:101,代码来源:XhtmlValidate.py

示例12: xhtmlValidate

def xhtmlValidate(modelXbrl, elt):
    from lxml.etree import DTD, XMLSyntaxError
    ixNsStartTags = ["{" + ns + "}" for ns in XbrlConst.ixbrlAll]
    
    def checkAttribute(elt, isIxElt, attrTag, attrValue):
        if attrTag.startswith("{"):
            ns, sep, localName = attrTag[1:].partition("}")
            if isIxElt:
                if ns not in (XbrlConst.xml, XbrlConst.xsi):
                    modelXbrl.error("ix:qualifiedAttributeNotExpected",
                        _("Inline XBRL element %(element)s: has qualified attribute %(name)s"),
                        modelObject=elt, element=str(elt.elementQname), name=attrTag)
            else:
                if ns in XbrlConst.ixbrlAll:
                    modelXbrl.error("ix:inlineAttributeMisplaced",
                        _("Inline XBRL attributes are not allowed on html elements: ix:%(name)s"),
                        modelObject=elt, name=localName)
                elif ns not in {XbrlConst.xml, XbrlConst.xsi, XbrlConst.xhtml}:
                    modelXbrl.error("ix:extensionAttributeMisplaced",
                        _("Extension attributes are not allowed on html elements: %(tag)s"),
                        modelObject=elt, tag=attrTag)
        elif isIxElt:
            try:
                _xsdType = ixAttrType[elt.namespaceURI][attrTag]
                if isinstance(_xsdType, dict):
                    baseXsdType = _xsdType["type"]
                    facets = _xsdType
                else:
                    baseXsdType = _xsdType
                    facets = None
                XmlValidate.validateValue(modelXbrl, elt, attrTag, baseXsdType, attrValue, facets=facets)
                
                disallowedXbrliAttrs = ({"scheme", "periodType", "balance", "contextRef", "unitRef", "precision", "decimals"} -
                                        {"fraction": {"contextRef", "unitRef"},
                                         "nonFraction": {"contextRef", "unitRef", "decimals", "precision"},
                                         "nonNumeric": {"contextRef"}}.get(elt.localName, set()))
                disallowedAttrs = [a for a in disallowedXbrliAttrs if elt.get(a) is not None]
                if disallowedAttrs:
                    modelXbrl.error("ix:inlineElementAttributes",
                        _("Inline XBRL element %(element)s has disallowed attributes %(attributes)s"),
                        modelObject=elt, element=elt.elementQname, attributes=", ".join(disallowedAttrs))
            except KeyError:
                modelXbrl.error("ix:attributeNotExpected",
                    _("Attribute %(attribute)s is not expected on element element ix:%(element)s"),
                    modelObject=elt, attribute=attrTag, element=elt.localName)
                
    def checkHierarchyConstraints(elt):
        constraints = ixHierarchyConstraints.get(elt.localName)
        if constraints:
            for _rel, names in constraints:
                reqt = _rel[0]
                rel = _rel[1:]
                if reqt in ('&', '^'):
                    nameFilter = ('*',)
                else:
                    nameFilter = names
                relations = {"ancestor": XmlUtil.ancestor, 
                             "parent": XmlUtil.parent, 
                             "child": XmlUtil.children, 
                             "descendant": XmlUtil.descendants}[rel](
                            elt, 
                            '*' if nameFilter == ('*',) else elt.namespaceURI,
                            nameFilter)
                if rel in ("ancestor", "parent"):
                    if relations is None: relations = []
                    else: relations = [relations]
                issue = ''
                if reqt == '^':
                    if not any(r.localName in names and r.namespaceURI == elt.namespaceURI
                               for r in relations):
                        issue = " and is missing one of " + ', '.join(names)
                if reqt in ('&', '^'):
                    disallowed = [str(r.elementQname)
                                  for r in relations
                                  if r.localName not in names or r.namespaceURI != elt.namespaceURI]
                    if disallowed:
                        issue += " and may not have " + ", ".join(disallowed)
                if reqt == '?' and len(relations) > 1:
                    issue = " may only have 0 or 1 but {0} present ".format(len(relations))
                if reqt == '+' and len(relations) == 0:
                    issue = " must have more than 1 but none present "
                if ((reqt == '+' and not relations) or
                    (reqt == '-' and relations) or
                    (issue)):
                    code = "ix:" + {
                           'ancestor': "ancestorNode",
                           'parent': "parentNode",
                           'child': "childNodes",
                           'descendant': "descendantNodes"}[rel] + {
                            '+': "Required",
                            '-': "Disallowed",
                            '&': "Allowed",
                            '^': "Specified"}.get(reqt, "Specified")
                    msg = _("Inline XBRL 1.0 ix:{0} {1} {2} {3} {4} element").format(
                                elt.localName,
                                {'+': "must", '-': "may not", '&': "may only",
                                 '?': "may", '+': "must"}[reqt],
                                {'ancestor': "be nested in",
                                 'parent': "have parent",
                                 'child': "have child",
#.........这里部分代码省略.........
开发者ID:PabTorre,项目名称:Arelle,代码行数:101,代码来源:XhtmlValidate.py

示例13: read

	def read(self, file):
		dtd = DTD(file)
		for entity in dtd.entities():
			unit = Unit(entity.name, entity.content)
			self.units.append(unit)
开发者ID:odonnellryan,项目名称:python-ttk2,代码行数:5,代码来源:dtd.py


注:本文中的lxml.etree.DTD类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。