31 from xml.sax.saxutils import escape, unescape, quoteattr |
31 from xml.sax.saxutils import escape, unescape, quoteattr |
32 from lxml import etree |
32 from lxml import etree |
33 from new import classobj |
33 from new import classobj |
34 from collections import OrderedDict |
34 from collections import OrderedDict |
35 |
35 |
|
36 |
36 def CreateNode(name): |
37 def CreateNode(name): |
37 node = minidom.Node() |
38 node = minidom.Node() |
38 node.nodeName = name |
39 node.nodeName = name |
39 node._attrs = {} |
40 node._attrs = {} |
40 node.childNodes = [] |
41 node.childNodes = [] |
41 return node |
42 return node |
42 |
43 |
|
44 |
43 def NodeRenameAttr(node, old_name, new_name): |
45 def NodeRenameAttr(node, old_name, new_name): |
44 node._attrs[new_name] = node._attrs.pop(old_name) |
46 node._attrs[new_name] = node._attrs.pop(old_name) |
|
47 |
45 |
48 |
46 def NodeSetAttr(node, name, value): |
49 def NodeSetAttr(node, name, value): |
47 attr = minidom.Attr(name) |
50 attr = minidom.Attr(name) |
48 text = minidom.Text() |
51 text = minidom.Text() |
49 text.data = value |
52 text.data = value |
71 """ |
74 """ |
72 time_model = re.compile('([0-9]{2}):([0-9]{2}):([0-9]{2}(?:\.[0-9]*)?)(?:Z)?$') |
75 time_model = re.compile('([0-9]{2}):([0-9]{2}):([0-9]{2}(?:\.[0-9]*)?)(?:Z)?$') |
73 date_model = re.compile('([0-9]{4})-([0-9]{2})-([0-9]{2})((?:[\-\+][0-9]{2}:[0-9]{2})|Z)?$') |
76 date_model = re.compile('([0-9]{4})-([0-9]{2})-([0-9]{2})((?:[\-\+][0-9]{2}:[0-9]{2})|Z)?$') |
74 datetime_model = re.compile('([0-9]{4})-([0-9]{2})-([0-9]{2})[ T]([0-9]{2}):([0-9]{2}):([0-9]{2}(?:\.[0-9]*)?)((?:[\-\+][0-9]{2}:[0-9]{2})|Z)?$') |
77 datetime_model = re.compile('([0-9]{4})-([0-9]{2})-([0-9]{2})[ T]([0-9]{2}):([0-9]{2}):([0-9]{2}(?:\.[0-9]*)?)((?:[\-\+][0-9]{2}:[0-9]{2})|Z)?$') |
75 |
78 |
|
79 |
76 class xml_timezone(datetime.tzinfo): |
80 class xml_timezone(datetime.tzinfo): |
77 |
81 |
78 def SetOffset(self, offset): |
82 def SetOffset(self, offset): |
79 if offset == "Z": |
83 if offset == "Z": |
80 self.__offset = timedelta(minutes = 0) |
84 self.__offset = timedelta(minutes = 0) |
96 |
100 |
97 [SYNTAXELEMENT, SYNTAXATTRIBUTE, SIMPLETYPE, COMPLEXTYPE, COMPILEDCOMPLEXTYPE, |
101 [SYNTAXELEMENT, SYNTAXATTRIBUTE, SIMPLETYPE, COMPLEXTYPE, COMPILEDCOMPLEXTYPE, |
98 ATTRIBUTESGROUP, ELEMENTSGROUP, ATTRIBUTE, ELEMENT, CHOICE, ANY, TAG, CONSTRAINT, |
102 ATTRIBUTESGROUP, ELEMENTSGROUP, ATTRIBUTE, ELEMENT, CHOICE, ANY, TAG, CONSTRAINT, |
99 ] = range(13) |
103 ] = range(13) |
100 |
104 |
|
105 |
101 def NotSupportedYet(type): |
106 def NotSupportedYet(type): |
102 """ |
107 """ |
103 Function that generates a function that point out to user that datatype |
108 Function that generates a function that point out to user that datatype |
104 used is not supported by xmlclass yet |
109 used is not supported by xmlclass yet |
105 @param type: data type |
110 @param type: data type |
108 def GetUnknownValue(attr): |
113 def GetUnknownValue(attr): |
109 raise ValueError("\"%s\" type isn't supported by \"xmlclass\" yet!" % \ |
114 raise ValueError("\"%s\" type isn't supported by \"xmlclass\" yet!" % \ |
110 type) |
115 type) |
111 return GetUnknownValue |
116 return GetUnknownValue |
112 |
117 |
113 """ |
118 |
114 This function calculates the number of whitespace for indentation |
|
115 """ |
|
116 def getIndent(indent, balise): |
119 def getIndent(indent, balise): |
|
120 """ |
|
121 This function calculates the number of whitespace for indentation |
|
122 """ |
117 first = indent * 2 |
123 first = indent * 2 |
118 second = first + len(balise) + 1 |
124 second = first + len(balise) + 1 |
119 return u'\t'.expandtabs(first), u'\t'.expandtabs(second) |
125 return u'\t'.expandtabs(first), u'\t'.expandtabs(second) |
120 |
126 |
121 |
127 |
533 raise ValueError("\"%s\" isn't a valid value for %s!" % \ |
539 raise ValueError("\"%s\" isn't a valid value for %s!" % \ |
534 (value, type)) |
540 (value, type)) |
535 return values |
541 return values |
536 return GetModelNameList |
542 return GetModelNameList |
537 |
543 |
|
544 |
538 def GenerateAnyInfos(infos): |
545 def GenerateAnyInfos(infos): |
539 |
546 |
540 def GetTextElement(tree): |
547 def GetTextElement(tree): |
541 if infos["namespace"][0] == "##any": |
548 if infos["namespace"][0] == "##any": |
542 return tree.xpath("p")[0] |
549 return tree.xpath("p")[0] |
562 "extract": ExtractAny, |
569 "extract": ExtractAny, |
563 "generate": GenerateAny, |
570 "generate": GenerateAny, |
564 "initial": InitialAny, |
571 "initial": InitialAny, |
565 "check": lambda x: isinstance(x, (StringType, UnicodeType, etree.ElementBase)) |
572 "check": lambda x: isinstance(x, (StringType, UnicodeType, etree.ElementBase)) |
566 } |
573 } |
|
574 |
567 |
575 |
568 def GenerateTagInfos(infos): |
576 def GenerateTagInfos(infos): |
569 def ExtractTag(tree): |
577 def ExtractTag(tree): |
570 if len(tree._attrs) > 0: |
578 if len(tree._attrs) > 0: |
571 raise ValueError("\"%s\" musn't have attributes!" % infos["name"]) |
579 raise ValueError("\"%s\" musn't have attributes!" % infos["name"]) |
589 "generate": GenerateTag, |
597 "generate": GenerateTag, |
590 "initial": lambda: None, |
598 "initial": lambda: None, |
591 "check": lambda x: x == None or infos["minOccurs"] == 0 and value == True |
599 "check": lambda x: x == None or infos["minOccurs"] == 0 and value == True |
592 } |
600 } |
593 |
601 |
|
602 |
594 def FindTypeInfos(factory, infos): |
603 def FindTypeInfos(factory, infos): |
595 if isinstance(infos, (UnicodeType, StringType)): |
604 if isinstance(infos, (UnicodeType, StringType)): |
596 namespace, name = DecomposeQualifiedName(infos) |
605 namespace, name = DecomposeQualifiedName(infos) |
597 return factory.GetQualifiedNameInfos(name, namespace) |
606 return factory.GetQualifiedNameInfos(name, namespace) |
598 return infos |
607 return infos |
|
608 |
599 |
609 |
600 def GetElementInitialValue(factory, infos): |
610 def GetElementInitialValue(factory, infos): |
601 infos["elmt_type"] = FindTypeInfos(factory, infos["elmt_type"]) |
611 infos["elmt_type"] = FindTypeInfos(factory, infos["elmt_type"]) |
602 if infos["minOccurs"] == 1: |
612 if infos["minOccurs"] == 1: |
603 element_name = factory.etreeNamespaceFormat % infos["name"] |
613 element_name = factory.etreeNamespaceFormat % infos["name"] |
614 value._init_() |
624 value._init_() |
615 return value |
625 return value |
616 return [initial_value() for i in xrange(infos["minOccurs"])] |
626 return [initial_value() for i in xrange(infos["minOccurs"])] |
617 else: |
627 else: |
618 return [] |
628 return [] |
|
629 |
619 |
630 |
620 def GetContentInfos(name, choices): |
631 def GetContentInfos(name, choices): |
621 for choice_infos in choices: |
632 for choice_infos in choices: |
622 if choices_infos["type"] == "sequence": |
633 if choices_infos["type"] == "sequence": |
623 for element_infos in choices_infos["elements"]: |
634 for element_infos in choices_infos["elements"]: |
627 elif element_infos["name"] == name: |
638 elif element_infos["name"] == name: |
628 return choices_infos |
639 return choices_infos |
629 elif choice_infos["name"] == name: |
640 elif choice_infos["name"] == name: |
630 return choices_infos |
641 return choices_infos |
631 return None |
642 return None |
|
643 |
632 |
644 |
633 def ComputeContentChoices(factory, name, infos): |
645 def ComputeContentChoices(factory, name, infos): |
634 choices = [] |
646 choices = [] |
635 for choice in infos["choices"]: |
647 for choice in infos["choices"]: |
636 if choice["type"] == "sequence": |
648 if choice["type"] == "sequence": |
648 if choice_infos is not None: |
660 if choice_infos is not None: |
649 choice["elmt_type"] = choice_infos |
661 choice["elmt_type"] = choice_infos |
650 choices.append((choice["name"], choice)) |
662 choices.append((choice["name"], choice)) |
651 return choices |
663 return choices |
652 |
664 |
|
665 |
653 def GenerateContentInfos(factory, name, choices): |
666 def GenerateContentInfos(factory, name, choices): |
654 choices_dict = {} |
667 choices_dict = {} |
655 for choice_name, infos in choices: |
668 for choice_name, infos in choices: |
656 if choice_name == "sequence": |
669 if choice_name == "sequence": |
657 for element in infos["elements"]: |
670 for element in infos["elements"]: |
697 raise ValueError("\"%s\" isn't a valid QName value!" % name) |
710 raise ValueError("\"%s\" isn't a valid QName value!" % name) |
698 parts = result.groups()[0].split(':') |
711 parts = result.groups()[0].split(':') |
699 if len(parts) == 1: |
712 if len(parts) == 1: |
700 return None, parts[0] |
713 return None, parts[0] |
701 return parts |
714 return parts |
|
715 |
702 |
716 |
703 def GenerateElement(element_name, attributes, elements_model, |
717 def GenerateElement(element_name, attributes, elements_model, |
704 accept_text=False): |
718 accept_text=False): |
705 def ExtractElement(factory, node): |
719 def ExtractElement(factory, node): |
706 attrs = factory.ExtractNodeAttrs(element_name, node, attributes) |
720 attrs = factory.ExtractNodeAttrs(element_name, node, attributes) |
733 children.append(infos["extract"]["default"](factory, child)) |
747 children.append(infos["extract"]["default"](factory, child)) |
734 return node.nodeName, attrs, children |
748 return node.nodeName, attrs, children |
735 return ExtractElement |
749 return ExtractElement |
736 |
750 |
737 |
751 |
738 """ |
|
739 Class that generate class from an XML Tree |
|
740 """ |
|
741 class ClassFactory: |
752 class ClassFactory: |
|
753 """ |
|
754 Class that generate class from an XML Tree |
|
755 """ |
742 |
756 |
743 def __init__(self, document, filepath=None, debug=False): |
757 def __init__(self, document, filepath=None, debug=False): |
744 self.Document = document |
758 self.Document = document |
745 if filepath is not None: |
759 if filepath is not None: |
746 self.BaseFolder, self.FileName = os.path.split(filepath) |
760 self.BaseFolder, self.FileName = os.path.split(filepath) |
1189 classnames = self.XMLClassDefinitions.keys() |
1203 classnames = self.XMLClassDefinitions.keys() |
1190 classnames.sort() |
1204 classnames.sort() |
1191 for classname in classnames: |
1205 for classname in classnames: |
1192 print classname |
1206 print classname |
1193 |
1207 |
1194 """ |
1208 |
1195 Method that generate the method for generating the xml tree structure model by |
|
1196 following the attributes list defined |
|
1197 """ |
|
1198 def ComputeMultiplicity(name, infos): |
1209 def ComputeMultiplicity(name, infos): |
|
1210 """ |
|
1211 Method that generate the method for generating the xml tree structure model by |
|
1212 following the attributes list defined |
|
1213 """ |
1199 if infos["minOccurs"] == 0: |
1214 if infos["minOccurs"] == 0: |
1200 if infos["maxOccurs"] == "unbounded": |
1215 if infos["maxOccurs"] == "unbounded": |
1201 return "(?:%s)*" % name |
1216 return "(?:%s)*" % name |
1202 elif infos["maxOccurs"] == 1: |
1217 elif infos["maxOccurs"] == 1: |
1203 return "(?:%s)?" % name |
1218 return "(?:%s)?" % name |
1214 if infos["maxOccurs"] == "unbounded": |
1229 if infos["maxOccurs"] == "unbounded": |
1215 return "(?:%s){%d,}" % (name, infos["minOccurs"], name) |
1230 return "(?:%s){%d,}" % (name, infos["minOccurs"], name) |
1216 else: |
1231 else: |
1217 return "(?:%s){%d,%d}" % (name, infos["minOccurs"], |
1232 return "(?:%s){%d,%d}" % (name, infos["minOccurs"], |
1218 infos["maxOccurs"]) |
1233 infos["maxOccurs"]) |
|
1234 |
1219 |
1235 |
1220 def GetStructurePattern(classinfos): |
1236 def GetStructurePattern(classinfos): |
1221 base_structure_pattern = ( |
1237 base_structure_pattern = ( |
1222 classinfos["base"].StructurePattern.pattern[:-1] |
1238 classinfos["base"].StructurePattern.pattern[:-1] |
1223 if classinfos.has_key("base") else "") |
1239 if classinfos.has_key("base") else "") |
1243 if classinfos.get("order", True) or len(elements) == 0: |
1259 if classinfos.get("order", True) or len(elements) == 0: |
1244 return re.compile(base_structure_pattern + "".join(elements) + "$") |
1260 return re.compile(base_structure_pattern + "".join(elements) + "$") |
1245 else: |
1261 else: |
1246 raise ValueError("XSD structure not yet supported!") |
1262 raise ValueError("XSD structure not yet supported!") |
1247 |
1263 |
1248 """ |
1264 |
1249 Method that generate the method for creating a class instance |
|
1250 """ |
|
1251 def generateClassCreateFunction(class_definition): |
1265 def generateClassCreateFunction(class_definition): |
|
1266 """ |
|
1267 Method that generate the method for creating a class instance |
|
1268 """ |
1252 def classCreatefunction(): |
1269 def classCreatefunction(): |
1253 return class_definition() |
1270 return class_definition() |
1254 return classCreatefunction |
1271 return classCreatefunction |
|
1272 |
1255 |
1273 |
1256 def generateGetattrMethod(factory, class_definition, classinfos): |
1274 def generateGetattrMethod(factory, class_definition, classinfos): |
1257 attributes = dict([(attr["name"], attr) for attr in classinfos["attributes"] if attr["use"] != "prohibited"]) |
1275 attributes = dict([(attr["name"], attr) for attr in classinfos["attributes"] if attr["use"] != "prohibited"]) |
1258 optional_attributes = dict([(attr["name"], True) for attr in classinfos["attributes"] if attr["use"] == "optional"]) |
1276 optional_attributes = dict([(attr["name"], True) for attr in classinfos["attributes"] if attr["use"] == "optional"]) |
1259 elements = dict([(element["name"], element) for element in classinfos["elements"]]) |
1277 elements = dict([(element["name"], element) for element in classinfos["elements"]]) |
1305 |
1323 |
1306 return DefaultElementClass.__getattribute__(self, name) |
1324 return DefaultElementClass.__getattribute__(self, name) |
1307 |
1325 |
1308 return getattrMethod |
1326 return getattrMethod |
1309 |
1327 |
|
1328 |
1310 def generateSetattrMethod(factory, class_definition, classinfos): |
1329 def generateSetattrMethod(factory, class_definition, classinfos): |
1311 attributes = dict([(attr["name"], attr) for attr in classinfos["attributes"] if attr["use"] != "prohibited"]) |
1330 attributes = dict([(attr["name"], attr) for attr in classinfos["attributes"] if attr["use"] != "prohibited"]) |
1312 optional_attributes = dict([(attr["name"], True) for attr in classinfos["attributes"] if attr["use"] == "optional"]) |
1331 optional_attributes = dict([(attr["name"], True) for attr in classinfos["attributes"] if attr["use"] == "optional"]) |
1313 elements = OrderedDict([(element["name"], element) for element in classinfos["elements"]]) |
1332 elements = OrderedDict([(element["name"], element) for element in classinfos["elements"]]) |
1314 |
1333 |
1372 |
1391 |
1373 else: |
1392 else: |
1374 raise AttributeError("'%s' can't have an attribute '%s'." % (self.__class__.__name__, name)) |
1393 raise AttributeError("'%s' can't have an attribute '%s'." % (self.__class__.__name__, name)) |
1375 |
1394 |
1376 return setattrMethod |
1395 return setattrMethod |
|
1396 |
1377 |
1397 |
1378 def gettypeinfos(name, facets): |
1398 def gettypeinfos(name, facets): |
1379 if facets.has_key("enumeration") and facets["enumeration"][0] is not None: |
1399 if facets.has_key("enumeration") and facets["enumeration"][0] is not None: |
1380 return facets["enumeration"][0] |
1400 return facets["enumeration"][0] |
1381 elif facets.has_key("maxInclusive"): |
1401 elif facets.has_key("maxInclusive"): |
1390 limits["min"] = facets["minExclusive"][0] + 1 |
1410 limits["min"] = facets["minExclusive"][0] + 1 |
1391 if limits["max"] is not None or limits["min"] is not None: |
1411 if limits["max"] is not None or limits["min"] is not None: |
1392 return limits |
1412 return limits |
1393 return name |
1413 return name |
1394 |
1414 |
|
1415 |
1395 def generateGetElementAttributes(factory, classinfos): |
1416 def generateGetElementAttributes(factory, classinfos): |
1396 def getElementAttributes(self): |
1417 def getElementAttributes(self): |
1397 attr_list = [] |
1418 attr_list = [] |
1398 if classinfos.has_key("base"): |
1419 if classinfos.has_key("base"): |
1399 attr_list.extend(classinfos["base"].getElementAttributes(self)) |
1420 attr_list.extend(classinfos["base"].getElementAttributes(self)) |
1403 "type" : gettypeinfos(attr["attr_type"]["basename"], attr["attr_type"]["facets"]), |
1424 "type" : gettypeinfos(attr["attr_type"]["basename"], attr["attr_type"]["facets"]), |
1404 "value" : getattr(self, attr["name"], "")} |
1425 "value" : getattr(self, attr["name"], "")} |
1405 attr_list.append(attr_params) |
1426 attr_list.append(attr_params) |
1406 return attr_list |
1427 return attr_list |
1407 return getElementAttributes |
1428 return getElementAttributes |
|
1429 |
1408 |
1430 |
1409 def generateGetElementInfos(factory, classinfos): |
1431 def generateGetElementInfos(factory, classinfos): |
1410 attributes = dict([(attr["name"], attr) for attr in classinfos["attributes"] if attr["use"] != "prohibited"]) |
1432 attributes = dict([(attr["name"], attr) for attr in classinfos["attributes"] if attr["use"] != "prohibited"]) |
1411 elements = dict([(element["name"], element) for element in classinfos["elements"]]) |
1433 elements = dict([(element["name"], element) for element in classinfos["elements"]]) |
1412 |
1434 |
1473 if instance is None: |
1495 if instance is None: |
1474 instance = element["elmt_type"]["initial"]() |
1496 instance = element["elmt_type"]["initial"]() |
1475 children.append(instance.getElementInfos(element_name)) |
1497 children.append(instance.getElementInfos(element_name)) |
1476 return {"name": name, "type": attr_type, "value": value, "use": use, "children": children} |
1498 return {"name": name, "type": attr_type, "value": value, "use": use, "children": children} |
1477 return getElementInfos |
1499 return getElementInfos |
|
1500 |
1478 |
1501 |
1479 def generateSetElementValue(factory, classinfos): |
1502 def generateSetElementValue(factory, classinfos): |
1480 attributes = dict([(attr["name"], attr) for attr in classinfos["attributes"] if attr["use"] != "prohibited"]) |
1503 attributes = dict([(attr["name"], attr) for attr in classinfos["attributes"] if attr["use"] != "prohibited"]) |
1481 elements = dict([(element["name"], element) for element in classinfos["elements"]]) |
1504 elements = dict([(element["name"], element) for element in classinfos["elements"]]) |
1482 |
1505 |
1530 raise ValueError("\"content\" element is required!") |
1553 raise ValueError("\"content\" element is required!") |
1531 else: |
1554 else: |
1532 self.setcontentbytype(value) |
1555 self.setcontentbytype(value) |
1533 return setElementValue |
1556 return setElementValue |
1534 |
1557 |
1535 """ |
1558 |
1536 Methods that generates the different methods for setting and getting the attributes |
|
1537 """ |
|
1538 def generateInitMethod(factory, classinfos): |
1559 def generateInitMethod(factory, classinfos): |
|
1560 """ |
|
1561 Methods that generates the different methods for setting and getting the attributes |
|
1562 """ |
|
1563 |
1539 def initMethod(self): |
1564 def initMethod(self): |
1540 if classinfos.has_key("base"): |
1565 if classinfos.has_key("base"): |
1541 classinfos["base"]._init_(self) |
1566 classinfos["base"]._init_(self) |
1542 for attribute in classinfos["attributes"]: |
1567 for attribute in classinfos["attributes"]: |
1543 attribute["attr_type"] = FindTypeInfos(factory, attribute["attr_type"]) |
1568 attribute["attr_type"] = FindTypeInfos(factory, attribute["attr_type"]) |
1552 initial = GetElementInitialValue(factory, element) |
1577 initial = GetElementInitialValue(factory, element) |
1553 if initial is not None: |
1578 if initial is not None: |
1554 map(self.append, initial) |
1579 map(self.append, initial) |
1555 return initMethod |
1580 return initMethod |
1556 |
1581 |
|
1582 |
1557 def generateSetMethod(attr): |
1583 def generateSetMethod(attr): |
1558 def setMethod(self, value): |
1584 def setMethod(self, value): |
1559 setattr(self, attr, value) |
1585 setattr(self, attr, value) |
1560 return setMethod |
1586 return setMethod |
1561 |
1587 |
|
1588 |
1562 def generateGetMethod(attr): |
1589 def generateGetMethod(attr): |
1563 def getMethod(self): |
1590 def getMethod(self): |
1564 return getattr(self, attr, None) |
1591 return getattr(self, attr, None) |
1565 return getMethod |
1592 return getMethod |
|
1593 |
1566 |
1594 |
1567 def generateAddMethod(attr, factory, infos): |
1595 def generateAddMethod(attr, factory, infos): |
1568 def addMethod(self): |
1596 def addMethod(self): |
1569 if infos["type"] == ATTRIBUTE: |
1597 if infos["type"] == ATTRIBUTE: |
1570 infos["attr_type"] = FindTypeInfos(factory, infos["attr_type"]) |
1598 infos["attr_type"] = FindTypeInfos(factory, infos["attr_type"]) |
1578 value._init_() |
1606 value._init_() |
1579 else: |
1607 else: |
1580 raise ValueError("Invalid class attribute!") |
1608 raise ValueError("Invalid class attribute!") |
1581 return addMethod |
1609 return addMethod |
1582 |
1610 |
|
1611 |
1583 def generateDeleteMethod(attr): |
1612 def generateDeleteMethod(attr): |
1584 def deleteMethod(self): |
1613 def deleteMethod(self): |
1585 setattr(self, attr, None) |
1614 setattr(self, attr, None) |
1586 return deleteMethod |
1615 return deleteMethod |
|
1616 |
1587 |
1617 |
1588 def generateAppendMethod(attr, maxOccurs, factory, infos): |
1618 def generateAppendMethod(attr, maxOccurs, factory, infos): |
1589 def appendMethod(self, value): |
1619 def appendMethod(self, value): |
1590 infos["elmt_type"] = FindTypeInfos(factory, infos["elmt_type"]) |
1620 infos["elmt_type"] = FindTypeInfos(factory, infos["elmt_type"]) |
1591 attr_list = getattr(self, attr) |
1621 attr_list = getattr(self, attr) |
1595 else: |
1625 else: |
1596 attr_list[-1].addnext(value) |
1626 attr_list[-1].addnext(value) |
1597 else: |
1627 else: |
1598 raise ValueError("There can't be more than %d values in \"%s\"!" % (maxOccurs, attr)) |
1628 raise ValueError("There can't be more than %d values in \"%s\"!" % (maxOccurs, attr)) |
1599 return appendMethod |
1629 return appendMethod |
|
1630 |
1600 |
1631 |
1601 def generateInsertMethod(attr, maxOccurs, factory, infos): |
1632 def generateInsertMethod(attr, maxOccurs, factory, infos): |
1602 def insertMethod(self, index, value): |
1633 def insertMethod(self, index, value): |
1603 infos["elmt_type"] = FindTypeInfos(factory, infos["elmt_type"]) |
1634 infos["elmt_type"] = FindTypeInfos(factory, infos["elmt_type"]) |
1604 attr_list = getattr(self, attr) |
1635 attr_list = getattr(self, attr) |
1611 attr_list[min(index - 1, len(attr_list) - 1)].addnext(value) |
1642 attr_list[min(index - 1, len(attr_list) - 1)].addnext(value) |
1612 else: |
1643 else: |
1613 raise ValueError("There can't be more than %d values in \"%s\"!" % (maxOccurs, attr)) |
1644 raise ValueError("There can't be more than %d values in \"%s\"!" % (maxOccurs, attr)) |
1614 return insertMethod |
1645 return insertMethod |
1615 |
1646 |
|
1647 |
1616 def generateGetChoicesMethod(choice_types): |
1648 def generateGetChoicesMethod(choice_types): |
1617 def getChoicesMethod(self): |
1649 def getChoicesMethod(self): |
1618 return [choice["name"] for choice in choice_types] |
1650 return [choice["name"] for choice in choice_types] |
1619 return getChoicesMethod |
1651 return getChoicesMethod |
|
1652 |
1620 |
1653 |
1621 def generateSetChoiceByTypeMethod(factory, choice_types): |
1654 def generateSetChoiceByTypeMethod(factory, choice_types): |
1622 choices = dict([(choice["name"], choice) for choice in choice_types]) |
1655 choices = dict([(choice["name"], choice) for choice in choice_types]) |
1623 def setChoiceMethod(self, content_type): |
1656 def setChoiceMethod(self, content_type): |
1624 if not choices.has_key(content_type): |
1657 if not choices.has_key(content_type): |
1628 DefaultElementClass.__setattr__(new_content, "tag", factory.etreeNamespaceFormat % content_type) |
1661 DefaultElementClass.__setattr__(new_content, "tag", factory.etreeNamespaceFormat % content_type) |
1629 self.content = new_content |
1662 self.content = new_content |
1630 return new_content |
1663 return new_content |
1631 return setChoiceMethod |
1664 return setChoiceMethod |
1632 |
1665 |
|
1666 |
1633 def generateAppendChoiceByTypeMethod(maxOccurs, factory, choice_types): |
1667 def generateAppendChoiceByTypeMethod(maxOccurs, factory, choice_types): |
1634 choices = dict([(choice["name"], choice) for choice in choice_types]) |
1668 choices = dict([(choice["name"], choice) for choice in choice_types]) |
1635 def appendChoiceMethod(self, content_type): |
1669 def appendChoiceMethod(self, content_type): |
1636 if not choices.has_key(content_type): |
1670 if not choices.has_key(content_type): |
1637 raise ValueError("Unknown \"%s\" choice type for \"content\"!" % content_type) |
1671 raise ValueError("Unknown \"%s\" choice type for \"content\"!" % content_type) |
1643 return new_element |
1677 return new_element |
1644 else: |
1678 else: |
1645 raise ValueError("There can't be more than %d values in \"content\"!" % maxOccurs) |
1679 raise ValueError("There can't be more than %d values in \"content\"!" % maxOccurs) |
1646 return appendChoiceMethod |
1680 return appendChoiceMethod |
1647 |
1681 |
|
1682 |
1648 def generateInsertChoiceByTypeMethod(maxOccurs, factory, choice_types): |
1683 def generateInsertChoiceByTypeMethod(maxOccurs, factory, choice_types): |
1649 choices = dict([(choice["name"], choice) for choice in choice_types]) |
1684 choices = dict([(choice["name"], choice) for choice in choice_types]) |
1650 def insertChoiceMethod(self, index, content_type): |
1685 def insertChoiceMethod(self, index, content_type): |
1651 if not choices.has_key(content_type): |
1686 if not choices.has_key(content_type): |
1652 raise ValueError("Unknown \"%s\" choice type for \"content\"!" % content_type) |
1687 raise ValueError("Unknown \"%s\" choice type for \"content\"!" % content_type) |
1658 return new_element |
1693 return new_element |
1659 else: |
1694 else: |
1660 raise ValueError("There can't be more than %d values in \"content\"!" % maxOccurs) |
1695 raise ValueError("There can't be more than %d values in \"content\"!" % maxOccurs) |
1661 return insertChoiceMethod |
1696 return insertChoiceMethod |
1662 |
1697 |
|
1698 |
1663 def generateRemoveMethod(attr, minOccurs): |
1699 def generateRemoveMethod(attr, minOccurs): |
1664 def removeMethod(self, index): |
1700 def removeMethod(self, index): |
1665 attr_list = getattr(self, attr) |
1701 attr_list = getattr(self, attr) |
1666 if len(attr_list) > minOccurs: |
1702 if len(attr_list) > minOccurs: |
1667 self.remove(attr_list[index]) |
1703 self.remove(attr_list[index]) |
1668 else: |
1704 else: |
1669 raise ValueError("There can't be less than %d values in \"%s\"!" % (minOccurs, attr)) |
1705 raise ValueError("There can't be less than %d values in \"%s\"!" % (minOccurs, attr)) |
1670 return removeMethod |
1706 return removeMethod |
1671 |
1707 |
|
1708 |
1672 def generateCountMethod(attr): |
1709 def generateCountMethod(attr): |
1673 def countMethod(self): |
1710 def countMethod(self): |
1674 return len(getattr(self, attr)) |
1711 return len(getattr(self, attr)) |
1675 return countMethod |
1712 return countMethod |
1676 |
1713 |
1690 def getLocalTag(self): |
1728 def getLocalTag(self): |
1691 return etree.QName(self.tag).localname |
1729 return etree.QName(self.tag).localname |
1692 |
1730 |
1693 def tostring(self): |
1731 def tostring(self): |
1694 return NAMESPACE_PATTERN.sub("", etree.tostring(self, pretty_print=True, encoding='utf-8')).decode('utf-8') |
1732 return NAMESPACE_PATTERN.sub("", etree.tostring(self, pretty_print=True, encoding='utf-8')).decode('utf-8') |
|
1733 |
1695 |
1734 |
1696 class XMLElementClassLookUp(etree.PythonElementClassLookup): |
1735 class XMLElementClassLookUp(etree.PythonElementClassLookup): |
1697 |
1736 |
1698 def __init__(self, classes, *args, **kwargs): |
1737 def __init__(self, classes, *args, **kwargs): |
1699 etree.PythonElementClassLookup.__init__(self, *args, **kwargs) |
1738 etree.PythonElementClassLookup.__init__(self, *args, **kwargs) |
1725 if possible_class.StructurePattern.match(children) is not None: |
1764 if possible_class.StructurePattern.match(children) is not None: |
1726 return possible_class |
1765 return possible_class |
1727 return element_class[0] |
1766 return element_class[0] |
1728 return element_class |
1767 return element_class |
1729 |
1768 |
|
1769 |
1730 class XMLClassParser(etree.XMLParser): |
1770 class XMLClassParser(etree.XMLParser): |
1731 |
1771 |
1732 def __init__(self, namespaces, default_namespace_format, base_class, xsd_schema, *args, **kwargs): |
1772 def __init__(self, namespaces, default_namespace_format, base_class, xsd_schema, *args, **kwargs): |
1733 etree.XMLParser.__init__(self, *args, **kwargs) |
1773 etree.XMLParser.__init__(self, *args, **kwargs) |
1734 self.DefaultNamespaceFormat = default_namespace_format |
1774 self.DefaultNamespaceFormat = default_namespace_format |
1787 new_element = element_class() |
1827 new_element = element_class() |
1788 DefaultElementClass.__setattr__(new_element, "tag", self.DefaultNamespaceFormat % element_tag) |
1828 DefaultElementClass.__setattr__(new_element, "tag", self.DefaultNamespaceFormat % element_tag) |
1789 new_element._init_() |
1829 new_element._init_() |
1790 return new_element |
1830 return new_element |
1791 |
1831 |
|
1832 |
1792 def GenerateParser(factory, xsdstring): |
1833 def GenerateParser(factory, xsdstring): |
1793 ComputedClasses = factory.CreateClasses() |
1834 ComputedClasses = factory.CreateClasses() |
1794 |
1835 |
1795 if factory.FileName is not None: |
1836 if factory.FileName is not None: |
1796 ComputedClasses = ComputedClasses[factory.FileName] |
1837 ComputedClasses = ComputedClasses[factory.FileName] |