本文整理汇总了Python中lxml.etree.DTD.validate方法的典型用法代码示例。如果您正苦于以下问题:Python DTD.validate方法的具体用法?Python DTD.validate怎么用?Python DTD.validate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类lxml.etree.DTD
的用法示例。
在下文中一共展示了DTD.validate方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: validate_norm
# 需要导入模块: from lxml.etree import DTD [as 别名]
# 或者: from lxml.etree.DTD import validate [as 别名]
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)
示例2: normalize_samples
# 需要导入模块: from lxml.etree import DTD [as 别名]
# 或者: from lxml.etree.DTD import validate [as 别名]
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')))
self.assertTrue(dtd.validate(n))
# Create normalizer from xml definition
normalizer = Normalizer(n, os.path.join(self.normalizer_path, 'common_tagTypes.xml'))
self.assertEquals(normalizer.name, name)
self.assertEquals(normalizer.version, version)
self.assertTrue(normalizer.validate())
示例3: xhtmlValidate
# 需要导入模块: from lxml.etree import DTD [as 别名]
# 或者: from lxml.etree.DTD import validate [as 别名]
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())
示例4: test_00_validate_fake_syslog
# 需要导入模块: from lxml.etree import DTD [as 别名]
# 或者: from lxml.etree.DTD import validate [as 别名]
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))
示例5: __init__
# 需要导入模块: from lxml.etree import DTD [as 别名]
# 或者: from lxml.etree.DTD import validate [as 别名]
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_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()
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)
else:
normalizer = Normalizer(norm, os.path.join(self.normalizers_path, "common_tagTypes.xml"))
self.normalizers.setdefault(normalizer.appliedTo, [])
self.normalizers[normalizer.appliedTo].append(normalizer)
self.activate_normalizers()
def iter_normalizer(self):
""" Iterates through normalizers and returns the normalizers' paths.
@return: a generator of absolute paths.
"""
path = self.normalizers_path
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):
"""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.
"""
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"
path = self.normalizers_path
xmlconf.write(open(os.path.join(path, name), "w"), encoding="utf8", method="xml", pretty_print=True)
self.reload()
def get_normalizer_source(self, name):
"""Returns the raw XML source of normalizer name."""
try:
norm = [u for u in sum(self.normalizers.values(), []) if u.name == name][0]
return norm.get_source()
except:
raise ValueError, "Normalizer %s not found" % name
def activate_normalizers(self):
"""Activates normalizers according to what was set by calling
set_active_normalizers. If no call to the latter function has been
made so far, this method activates every normalizer."""
if not self.active_normalizers:
self.active_normalizers = dict([(n.name, True) for n in sum([v for v in self.normalizers.values()], [])])
# fool-proof the list
self.set_active_normalizers(self.active_normalizers)
# build an ordered cache to speed things up
self._cache = []
#.........这里部分代码省略.........
示例6: xhtmlValidate
# 需要导入模块: from lxml.etree import DTD [as 别名]
# 或者: from lxml.etree.DTD import validate [as 别名]
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,
#.........这里部分代码省略.........
示例7: LogNormalizer
# 需要导入模块: from lxml.etree import DTD [as 别名]
# 或者: from lxml.etree.DTD import validate [as 别名]
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'
#.........这里部分代码省略.........
示例8: xhtmlValidate
# 需要导入模块: from lxml.etree import DTD [as 别名]
# 或者: from lxml.etree.DTD import validate [as 别名]
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
#.........这里部分代码省略.........
示例9: xhtmlValidate
# 需要导入模块: from lxml.etree import DTD [as 别名]
# 或者: from lxml.etree.DTD import validate [as 别名]
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",
#.........这里部分代码省略.........