File size: 125,971 Bytes
985c397 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 | #!/usr/bin/env python
# SPDX-License-Identifier: MIT
## LICENSE
## Copyright (c) 2003 Dave Kuhlman
## Permission is hereby granted, free of charge, to any person obtaining
## a copy of this software and associated documentation files (the
## "Software"), to deal in the Software without restriction, including
## without limitation the rights to use, copy, modify, merge, publish,
## distribute, sublicense, and/or sell copies of the Software, and to
## permit persons to whom the Software is furnished to do so, subject to
## the following conditions:
## The above copyright notice and this permission notice shall be
## included in all copies or substantial portions of the Software.
## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
## EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
## MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
## IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
## CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
## TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
## SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import sys
import os.path
import time
import getopt
from urllib.request import urlopen
from urllib.error import HTTPError
from xml.sax import handler, make_parser
import xml.sax.xmlreader
##from IPython.Shell import IPShellEmbed
##args = ''
##ipshell = IPShellEmbed(args,
## banner = 'Dropping into IPython',
## exit_msg = 'Leaving Interpreter, back to program.')
# Then use the following line where and when you want to drop into the
# IPython shell:
# ipshell('<some message> -- Entering ipshell.\\nHit Ctrl-D to exit')
#
# Global variables etc.
#
GenerateProperties = 0
DelayedElements = []
DelayedElements_subclass = []
AlreadyGenerated = []
AlreadyGenerated_subclass = []
PostponedExtensions = []
ElementsForSubclasses = []
ElementDict = {}
SaxElementDict = {}
ElementDebugList = []
Force = 0
NameTable = {
"class": "klass",
"import": "emport",
"type": "ttype",
}
SubclassSuffix = "Sub"
RootElement = None
AttributeGroups = {}
SubstitutionGroups = {}
#
# SubstitutionGroups can also include simple types that are
# not (defined) elements. Keep a list of these simple types.
# These are simple types defined at top level.
SimpleElementDict = {}
def set_type_constants(nameSpace):
global StringType, TokenType, IntegerType, DecimalType, ShortType, LongType, PositiveIntegerType, NegativeIntegerType, NonPositiveIntegerType, NonNegativeIntegerType, BooleanType, FloatType, DoubleType, ElementType, ComplexTypeType, SequenceType, ChoiceType, AttributeGroupType, AttributeType, SchemaType, DateTimeType, DateType, ComplexContentType, ExtensionType, IDType, IDREFType, IDREFSType, AnyAttributeType
AttributeGroupType = nameSpace + "attributeGroup"
AttributeType = nameSpace + "attribute"
BooleanType = nameSpace + "boolean"
ChoiceType = nameSpace + "choice"
ComplexContentType = nameSpace + "complexContent"
ComplexTypeType = nameSpace + "complexType"
AnyAttributeType = nameSpace + "anyAttribute"
DateTimeType = nameSpace + "dateTime"
DateType = nameSpace + "date"
IntegerType = (
nameSpace + "integer",
nameSpace + "xs:unsignedShort",
nameSpace + "short",
nameSpace + "long",
)
# ShortType = nameSpace + 'short'
# LongType = nameSpace + 'long'
DecimalType = nameSpace + "decimal"
PositiveIntegerType = nameSpace + "positiveInteger"
NegativeIntegerType = nameSpace + "negativeInteger"
NonPositiveIntegerType = nameSpace + "nonPositiveInteger"
NonNegativeIntegerType = nameSpace + "nonNegativeInteger"
DoubleType = nameSpace + "double"
ElementType = nameSpace + "element"
ExtensionType = nameSpace + "extension"
FloatType = nameSpace + "float"
IDREFSType = nameSpace + "IDREFS"
IDREFType = nameSpace + "IDREF"
IDType = nameSpace + "ID"
SchemaType = nameSpace + "schema"
SequenceType = nameSpace + "sequence"
StringType = (
nameSpace + "string",
nameSpace + "duration",
nameSpace + "anyURI",
)
TokenType = nameSpace + "token"
#
# For debugging.
#
# Print only if DEBUG is true.
DEBUG = 1
def dbgprint(level, msg):
if DEBUG and level > 0:
print(msg)
def pplist(lst):
for count, item in enumerate(lst):
print("%d. %s" % (count, item))
#
# Representation of element definition.
#
def showLevel(outfile, level):
for idx in range(level):
outfile.write(" ")
class XschemaElement:
def __init__(self, attrs):
self.cleanName = ""
self.attrs = dict(attrs)
name_val = ""
type_val = ""
ref_val = ""
if "name" in self.attrs:
name_val = strip_namespace(self.attrs["name"])
if "type" in self.attrs:
# fix
# type_val = strip_namespace(self.attrs['type'])
type_val = self.attrs["type"]
if "ref" in self.attrs:
ref_val = strip_namespace(self.attrs["ref"])
if type_val and not name_val:
name_val = type_val
if ref_val and not name_val:
name_val = ref_val
if ref_val and not type_val:
type_val = ref_val
if name_val:
self.attrs["name"] = name_val
if type_val:
self.attrs["type"] = type_val
if ref_val:
self.attrs["ref"] = ref_val
self.name = name_val
self.children = []
self.maxOccurs = 1
self.complex = 0
self.complexType = 0
self.type = "NoneType"
self.mixed = 0
self.base = None
self.mixedExtensionError = 0
# Attribute definitions for the correct element.
self.attributeDefs = {}
# Attribute definitions for the current attributeGroup, if there is one.
self.attributeGroup = None
# List of names of attributes for this element.
# We will add the attribute definitions in each of these groups
# to this element in annotate().
self.attributeGroupNameList = []
self.topLevel = 0
# Does this element contain an anyAttribute?
self.anyAttribute = 0
def addChild(self, element):
self.children.append(element)
def getChildren(self):
return self.children
def getName(self):
return self.name
def getCleanName(self):
return self.cleanName
def getUnmappedCleanName(self):
return self.unmappedCleanName
def setName(self, name):
self.name = name
def getAttrs(self):
return self.attrs
def setAttrs(self, attrs):
self.attrs = attrs
def getMaxOccurs(self):
return self.maxOccurs
def getRawType(self):
return self.type
def getType(self):
returnType = self.type
if self.type in ElementDict:
typeObj = ElementDict[self.type]
typeObjType = typeObj.getRawType()
if (
typeObjType in StringType
or typeObjType == TokenType
or typeObjType == DateTimeType
or typeObjType == DateType
or typeObjType in IntegerType
or typeObjType == DecimalType
or typeObjType == PositiveIntegerType
or typeObjType == NegativeIntegerType
or typeObjType == NonPositiveIntegerType
or typeObjType == NonNegativeIntegerType
or typeObjType == BooleanType
or typeObjType == FloatType
or typeObjType == DoubleType
):
returnType = typeObjType
return returnType
def isComplex(self):
return self.complex
def addAttributeDefs(self, attrs):
self.attributeDefs.append(attrs)
def getAttributeDefs(self):
return self.attributeDefs
def isMixed(self):
return self.mixed
def setMixed(self, mixed):
self.mixed = mixed
def setBase(self, base):
self.base = base
def getBase(self):
return self.base
def getMixedExtensionError(self):
return self.mixedExtensionError
def getAttributeGroups(self):
return self.attributeGroups
def addAttribute(self, name, attribute):
self.attributeGroups[name] = attribute
def setAttributeGroup(self, attributeGroup):
self.attributeGroup = attributeGroup
def getAttributeGroup(self):
return self.attributeGroup
def setTopLevel(self, topLevel):
self.topLevel = topLevel
def getTopLevel(self):
return self.topLevel
def setAnyAttribute(self, anyAttribute):
self.anyAttribute = anyAttribute
def getAnyAttribute(self):
return self.anyAttribute
def show(self, outfile, level):
showLevel(outfile, level)
outfile.write("Name: %s Type: %s\n" % (self.name, self.getType()))
showLevel(outfile, level)
outfile.write(" - Complex: %d MaxOccurs: %d\n" % (self.complex, self.maxOccurs))
showLevel(outfile, level)
outfile.write(" - Attrs: %s\n" % self.attrs)
showLevel(outfile, level)
outfile.write(" - AttributeDefs: %s\n" % self.attributeDefs)
# ipshell('(visit_title) Entering ipshell.\nHit Ctrl-D to exit')
for attr in self.getAttributeDefs():
key = attr["name"]
try:
value = attr["value"]
except:
value = "<empty>"
showLevel(outfile, level + 1)
outfile.write("key: %s value: %s\n" % (key, value))
for child in self.children:
child.show(outfile, level + 1)
def annotate(self):
self.collect_element_dict()
self.annotate_find_type()
self.annotate_tree()
self.fix_dup_names()
self.coerce_attr_types()
self.checkMixedBases()
def collect_element_dict(self):
base = self.getBase()
if (
self.getTopLevel()
or len(self.getChildren()) > 0
or len(self.getAttributeDefs()) > 0
or base
):
ElementDict[self.name] = self
for child in self.children:
child.collect_element_dict()
def element_is_complex(self):
pass
# If it is a mixed-content element and it is defined as
# an extension, then all of its bases (base, base of base, ...)
# must be mixed-content. Mark it as an error, if not.
def checkMixedBases(self):
self.checkMixedBasesChain(self, self.mixed)
for child in self.children:
child.checkMixedBases()
def checkMixedBasesChain(self, child, childMixed):
base = self.getBase()
if base and base in ElementDict:
parent = ElementDict[base]
if childMixed != parent.isMixed():
self.mixedExtensionError = 1
return
parent.checkMixedBasesChain(child, childMixed)
def resolve_type(self):
self.complex = 0
# If it has any attributes, then it's complex.
attrDefs = self.getAttributeDefs()
if len(attrDefs) > 0:
self.complex = 1
# type_val = ''
type_val = self.resolve_type_1()
if type_val:
if type_val in ElementDict:
element = ElementDict[type_val]
type_val1 = element.resolve_type_1()
if (
type_val1 in StringType
or type_val1 == TokenType
or type_val1 == DateTimeType
or type_val1 == DateType
or type_val1 in IntegerType
or type_val1 == DecimalType
or type_val1 == PositiveIntegerType
or type_val1 == NonPositiveIntegerType
or type_val1 == NegativeIntegerType
or type_val1 == NonNegativeIntegerType
or type_val1 == BooleanType
or type_val1 == FloatType
or type_val1 == DoubleType
):
type_val = type_val1
else:
self.complex = 1
else:
if (
type_val in StringType
or type_val == TokenType
or type_val == DateTimeType
or type_val == DateType
or type_val in IntegerType
or type_val == DecimalType
or type_val == PositiveIntegerType
or type_val == NonPositiveIntegerType
or type_val == NegativeIntegerType
or type_val == NonNegativeIntegerType
or type_val == BooleanType
or type_val == FloatType
or type_val == DoubleType
):
pass
else:
type_val = StringType[0]
else:
type_val = StringType[0]
return type_val
def resolve_type_1(self):
type_val = ""
if "type" in self.attrs:
# fix
# type_val = strip_namespace(self.attrs['type'])
type_val = self.attrs["type"]
elif "ref" in self.attrs:
# fix
type_val = strip_namespace(self.attrs["ref"])
# type_val = self.attrs['ref']
elif "name" in self.attrs:
# fix
type_val = strip_namespace(self.attrs["name"])
# type_val = self.attrs['name']
return type_val
def annotate_find_type(self):
type_val = self.resolve_type()
# dbgprint(1, '(aft) n: %s t: %s c: %s id: %s' % \
# (self.name, type_val, self.complex, id(self), ))
self.attrs["type"] = type_val
self.type = type_val
if not self.complex:
SimpleElementDict[self.name] = self.name
for child in self.children:
child.annotate_find_type()
def annotate_tree(self):
# If there is a namespace, replace it with an underscore.
if self.base:
self.base = strip_namespace(self.base)
self.unmappedCleanName = cleanupName(self.name)
self.cleanName = mapName(self.unmappedCleanName)
SaxElementDict[self.cleanName] = self
self.replace_attributeGroup_names()
if "maxOccurs" in self.attrs:
maxOccurs = self.attrs["maxOccurs"]
if maxOccurs == "unbounded":
maxOccurs = 99999
else:
try:
maxOccurs = int(self.attrs["maxOccurs"])
except ValueError:
sys.stderr.write(
'*** %s maxOccurs must be integer or "unbounded".' % (self.getName(),)
)
sys.exit(-1)
else:
maxOccurs = 1
self.maxOccurs = maxOccurs
# if self.cleanName == 'Reason_XXX':
# ipshell('(annotate_tree) -- Entering ipshell.\\nHit Ctrl-D to exit')
# If it does not have a type, then make the type the same as the name.
if self.type == "NoneType" and self.name:
self.type = self.name
# Is it a mixed-content element definition?
if "mixed" in self.attrs:
mixed = self.attrs["mixed"].strip()
if mixed == "1" or mixed.lower() == "true":
self.mixed = 1
# Do it recursively for all descendents.
for child in self.children:
child.annotate_tree()
#
# For each name in the attributeGroupNameList for this element,
# add the attributes defined for that name in the global
# attributeGroup dictionary.
def replace_attributeGroup_names(self):
for groupName in self.attributeGroupNameList:
if groupName in AttributeGroups:
attrGroup = AttributeGroups[groupName]
for name in attrGroup.getKeys():
attr = attrGroup.get(name)
self.attributeDefs[name] = attr
else:
print("*** Error. attributeGroup %s not defined." % groupName)
def __str__(self):
s1 = '<"%s" XschemaElement instance at 0x%x>' % (self.getName(), id(self))
return s1
def __repr__(self):
s1 = '<"%s" XschemaElement instance at 0x%x>' % (self.getName(), id(self))
return s1
def fix_dup_names(self):
# Patch-up names that are used for both a child element and an attribute.
#
attrDefs = self.getAttributeDefs()
# Collect a list of child element names.
# Must do this for base (extension) elements also.
elementNames = []
self.collectElementNames(elementNames)
replaced = []
# Create the needed new attributes.
keys = attrDefs.keys()
for key in keys:
attr = attrDefs[key]
name = attr.getName()
if name in elementNames:
newName = name + "_attr"
newAttr = XschemaAttribute(newName)
attrDefs[newName] = newAttr
replaced.append(name)
# Remove the old (replaced) attributes.
for name in replaced:
del attrDefs[name]
for child in self.children:
child.fix_dup_names()
def collectElementNames(self, elementNames):
for child in self.children:
elementNames.append(cleanupName(child.cleanName))
base = self.getBase()
if base and base in ElementDict:
parent = ElementDict[base]
parent.collectElementNames(elementNames)
def coerce_attr_types(self):
replacements = []
attrDefs = self.getAttributeDefs()
for idx, name in enumerate(attrDefs):
attr = attrDefs[name]
attrType = attr.getData_type()
if attrType == IDType or attrType == IDREFType or attrType == IDREFSType:
attr.setData_type(StringType[0])
for child in self.children:
child.coerce_attr_types()
# end class XschemaElement
class XschemaAttributeGroup:
def __init__(self, name="", group=None):
self.name = name
if group:
self.group = group
else:
self.group = {}
def setName(self, name):
self.name = name
def getName(self):
return self.name
def setGroup(self, group):
self.group = group
def getGroup(self):
return self.group
def get(self, name, default=None):
if name in self.group:
return self.group[name]
else:
return default
def getKeys(self):
return self.group.keys()
def add(self, name, attr):
self.group[name] = attr
def delete(self, name):
# if has_key(self.group, name):
if name in self.group:
del self.group[name]
return 1
else:
return 0
# end class XschemaAttributeGroup
class XschemaAttribute:
def __init__(self, name, data_type="xs:string", use="optional"):
self.name = name
self.data_type = data_type
self.use = use
def setName(self, name):
self.name = name
def getName(self):
return self.name
def setData_type(self, data_type):
self.data_type = data_type
def getData_type(self):
return self.data_type
def setUse(self, use):
self.use = use
def getUse(self):
return self.use
# end class XschemaAttribute
#
# SAX handler
#
class XschemaHandler(handler.ContentHandler):
def __init__(self):
handler.ContentHandler.__init__(self)
self.stack = []
self.root = None
self.inElement = 0
self.inComplexType = 0
self.inNonanonymousComplexType = 0
self.inSequence = 0
self.inChoice = 1
self.inAttribute = 0
self.inAttributeGroup = 0
self.inSimpleElement = 0
## self.dbgcount = 1
## self.dbgnames = []
def getRoot(self):
# ipshell('Returning root -- Entering ipshell.\\nHit Ctrl-D to exit')
return self.root
def showError(self, msg):
print(msg)
sys.exit(-1)
def startElement(self, name, attrs):
# dbgprint(1, 'before schema name: %s SchemaType: %s' % (name, SchemaType,))
if name == SchemaType:
# dbgprint(1, '(schema in)')
self.inSchema = 1
element = XschemaElement(attrs)
if len(self.stack) == 1:
element.setTopLevel(1)
self.stack.append(element)
# If there is an attribute "xmlns" and its value is
# "http://www.w3.org/2001/XMLSchema", then remember and
# use that namespace prefix.
for name, value in attrs.items():
if name[:6] == "xmlns:" and value == "http://www.w3.org/2001/XMLSchema":
nameSpace = name[6:] + ":"
set_type_constants(nameSpace)
elif name == ElementType or ((name == ComplexTypeType) and (len(self.stack) == 1)):
self.inElement = 1
self.inNonanonymousComplexType = 1
element = XschemaElement(attrs)
if len(self.stack) == 1:
element.setTopLevel(1)
if "substitutionGroup" in attrs and "name" in attrs:
substituteName = attrs["name"]
headName = attrs["substitutionGroup"]
if headName not in SubstitutionGroups:
SubstitutionGroups[headName] = []
SubstitutionGroups[headName].append(substituteName)
# dbgprint(1, '(startElement) added %s to %s' % (substituteName, headName))
if name == ComplexTypeType:
element.complexType = 1
self.stack.append(element)
elif name == ComplexTypeType:
# If it have any attributes and there is something on the stack,
# then copy the attributes to the item on top of the stack.
if len(self.stack) > 1 and len(attrs) > 0:
parentDict = self.stack[-1].getAttrs()
for key in attrs.keys():
parentDict[key] = attrs[key]
self.inComplexType = 1
elif name == SequenceType:
self.inSequence = 1
elif name == ChoiceType:
self.inChoice = 1
elif name == AttributeType:
self.inAttribute = 1
if "name" in attrs:
name = attrs["name"]
# fix-attribute-ref
elif "ref" in attrs:
name = strip_namespace(attrs["ref"])
else:
name = "no_attribute_name"
if "type" in attrs:
data_type = attrs["type"]
else:
data_type = StringType[0]
if "use" in attrs:
use = attrs["use"]
else:
use = "optional"
if self.stack[-1].attributeGroup:
# Add this attribute to a current attributeGroup.
attribute = XschemaAttribute(name, data_type, use)
self.stack[-1].attributeGroup.add(name, attribute)
else:
# Add this attribute to the element/complexType.
attribute = XschemaAttribute(name, data_type, use)
self.stack[-1].attributeDefs[name] = attribute
elif name == AttributeGroupType:
self.inAttributeGroup = 1
# If it has attribute 'name', then it's a definition.
# Prepare to save it as an attributeGroup.
if "name" in attrs:
name = strip_namespace(attrs["name"])
attributeGroup = XschemaAttributeGroup(name)
element = XschemaElement(attrs)
if len(self.stack) == 1:
element.setTopLevel(1)
element.setAttributeGroup(attributeGroup)
self.stack.append(element)
# If it has attribute 'ref', add it to the list of
# attributeGroups for this element/complexType.
if "ref" in attrs:
self.stack[-1].attributeGroupNameList.append(attrs["ref"])
elif name == ComplexContentType:
pass
elif name == ExtensionType:
if "base" in attrs and len(self.stack) > 0:
extensionBase = attrs["base"]
if (
extensionBase in StringType
or extensionBase == TokenType
or extensionBase == DateTimeType
or extensionBase == DateType
or extensionBase in IntegerType
or extensionBase == DecimalType
or extensionBase == PositiveIntegerType
or extensionBase == NegativeIntegerType
or extensionBase == NonPositiveIntegerType
or extensionBase == NonNegativeIntegerType
or extensionBase == BooleanType
or extensionBase == FloatType
or extensionBase == DoubleType
):
pass
else:
self.stack[-1].setBase(extensionBase)
elif name == AnyAttributeType:
# Mark the current element as containing anyAttribute.
self.stack[-1].setAnyAttribute(1)
def endElement(self, name):
if self.inSimpleElement:
self.inSimpleElement = 0
elif name == ElementType or (name == ComplexTypeType and self.stack[-1].complexType):
self.inElement = 0
self.inNonanonymousComplexType = 0
element = self.stack.pop()
self.stack[-1].addChild(element)
elif name == ComplexTypeType:
self.inComplexType = 0
elif name == SequenceType:
self.inSequence = 0
elif name == ChoiceType:
self.inChoice = 0
elif name == AttributeType:
self.inAttribute = 0
elif name == AttributeGroupType:
self.inAttributeGroup = 0
if self.stack[-1].attributeGroup:
# The top of the stack contains an XschemaElement which
# contains the definition of an attributeGroup.
# Save this attributeGroup in the
# global AttributeGroup dictionary.
attributeGroup = self.stack[-1].attributeGroup
name = attributeGroup.getName()
AttributeGroups[name] = attributeGroup
self.stack[-1].attributeGroup = None
self.stack.pop()
else:
# This is a reference to an attributeGroup.
# We have already added it to the list of attributeGroup names.
# Leave it. We'll fill it in during annotate.
pass
elif name == SchemaType:
self.inSchema = 0
if len(self.stack) != 1:
print("*** error stack. len(self.stack): %d" % len(self.stack))
sys.exit(-1)
self.root = self.stack[0]
elif name == ComplexContentType:
pass
elif name == ExtensionType:
pass
def characters(self, chrs):
if self.inElement:
pass
elif self.inComplexType:
pass
elif self.inSequence:
pass
elif self.inChoice:
pass
#
# Code generation
#
def generateExportFn_1(outfile, child, name, fill):
cleanName = cleanupName(name)
if (
child.getType() in StringType
or child.getType() == TokenType
or child.getType() == DateTimeType
or child.getType() == DateType
):
s1 = "%s showIndent(outfile, level)\n" % fill
outfile.write(s1)
s1 = "%s outfile.write('<%s>%%s</%s>\\n' %% quote_xml(self.get%s()))\n" % (
fill,
name,
name,
cleanName.capitalize(),
)
outfile.write(s1)
elif (
child.getType() in IntegerType
or child.getType() == BooleanType
or child.getType() == PositiveIntegerType
or child.getType() == NonPositiveIntegerType
or child.getType() == NegativeIntegerType
or child.getType() == NonNegativeIntegerType
):
s1 = "%s showIndent(outfile, level)\n" % fill
outfile.write(s1)
s1 = "%s outfile.write('<%s>%%d</%s>\\n' %% self.get%s())\n" % (
fill,
name,
name,
cleanName.capitalize(),
)
outfile.write(s1)
elif child.getType() == FloatType or child.getType() == DecimalType:
s1 = "%s showIndent(outfile, level)\n" % fill
outfile.write(s1)
s1 = "%s outfile.write('<%s>%%f</%s>\\n' %% self.get%s())\n" % (
fill,
name,
name,
cleanName.capitalize(),
)
outfile.write(s1)
elif child.getType() == DoubleType:
s1 = "%s showIndent(outfile, level)\n" % fill
outfile.write(s1)
s1 = "%s outfile.write('<%s>%%e</%s>\\n' %% self.get%s())\n" % (
fill,
name,
name,
cleanName.capitalize(),
)
outfile.write(s1)
else:
s1 = "%s if self.%s:\n" % (fill, cleanName)
outfile.write(s1)
if name == child.getType():
s1 = "%s self.%s.export(outfile, level)\n" % (fill, cleanName)
else:
s1 = "%s self.%s.export(outfile, level, name_='%s')\n" % (
fill,
cleanName,
name,
)
outfile.write(s1)
def generateExportFn_2(outfile, child, name, fill):
cleanName = cleanupName(name)
s1 = "%s for %s_ in self.get%s():\n" % (fill, cleanName, cleanName.capitalize())
outfile.write(s1)
if (
child.getType() in StringType
or child.getType() == TokenType
or child.getType() == DateTimeType
or child.getType() == DateType
):
s1 = "%s showIndent(outfile, level)\n" % fill
outfile.write(s1)
s1 = "%s outfile.write('<%s>%%s</%s>\\n' %% quote_xml(%s_))\n" % (
fill,
name,
name,
cleanName,
)
outfile.write(s1)
elif (
child.getType() in IntegerType
or child.getType() == BooleanType
or child.getType() == PositiveIntegerType
or child.getType() == NonPositiveIntegerType
or child.getType() == NegativeIntegerType
or child.getType() == NonNegativeIntegerType
):
s1 = "%s showIndent(outfile, level)\n" % fill
outfile.write(s1)
s1 = "%s outfile.write('<%s>%%d</%s>\\n' %% %s_)\n" % (
fill,
name,
name,
cleanName,
)
outfile.write(s1)
elif child.getType() == FloatType or child.getType() == DecimalType:
s1 = "%s showIndent(outfile, level)\n" % fill
outfile.write(s1)
s1 = "%s outfile.write('<%s>%%f</%s>\\n' %% %s_)\n" % (
fill,
name,
name,
cleanName,
)
outfile.write(s1)
elif child.getType() == DoubleType:
s1 = "%s showIndent(outfile, level)\n" % fill
outfile.write(s1)
s1 = "%s outfile.write('<%s>%%e</%s>\\n' %% %s_)\n" % (
fill,
name,
name,
cleanName,
)
outfile.write(s1)
else:
if name == child.getType():
s1 = "%s %s_.export(outfile, level)\n" % (fill, cleanName)
else:
s1 = "%s %s_.export(outfile, level, name_='%s')\n" % (
fill,
cleanName,
cleanName,
)
outfile.write(s1)
def generateExportAttributes(outfile, element, hasAttributes):
if len(element.getAttributeDefs()) > 0:
hasAttributes += 1
attrDefs = element.getAttributeDefs()
for key in attrDefs.keys():
attrDef = attrDefs[key]
name = attrDef.getName()
cleanName = cleanupName(name)
capName = cleanName.capitalize()
if attrDef.getUse() == "optional":
s1 = " if self.get%s() is not None:\n" % (capName,)
outfile.write(s1)
s1 = " outfile.write(' %s=\"%%s\"' %% (self.get%s(), ))\n" % (
name,
capName,
)
outfile.write(s1)
else:
s1 = " outfile.write(' %s=\"%%s\"' %% (self.get%s(), ))\n" % (
name,
capName,
)
outfile.write(s1)
if element.getAnyAttribute():
s1 = " for name, value in self.anyAttributes_.items():\n"
outfile.write(s1)
s1 = " outfile.write(' %s=\"%s\"' % (name, value, ))\n"
outfile.write(s1)
return hasAttributes
def generateExportChildren(outfile, element, hasChildren):
if len(element.getChildren()) > 0:
hasChildren += 1
if element.isMixed():
s1 = " for item_ in self.content_:\n"
outfile.write(s1)
s1 = " item_.export(outfile, level, name_)\n"
outfile.write(s1)
else:
for child in element.getChildren():
name = child.getName()
if child.getMaxOccurs() > 1:
generateExportFn_2(outfile, child, name, " ")
else:
generateExportFn_1(outfile, child, name, "")
## base = element.getBase()
## if base and base in ElementDict:
## parent = ElementDict[base]
## hasAttributes = generateExportChildren(outfile, parent, hasChildren)
return hasChildren
def countChildren(element, count):
count += len(element.getChildren())
base = element.getBase()
if base and base in ElementDict:
parent = ElementDict[base]
count = countChildren(parent, count)
return count
def generateExportFn(outfile, prefix, element):
base = element.getBase()
s1 = " def export(self, outfile, level, name_='%s'):\n" % element.getName()
outfile.write(s1)
s1 = " showIndent(outfile, level)\n"
outfile.write(s1)
if len(element.getAttributeDefs()) > 0:
s1 = " outfile.write('<%s' % (name_, ))\n"
outfile.write(s1)
s1 = " self.exportAttributes(outfile, level, name_='%s')\n" % element.getName()
outfile.write(s1)
if element.isMixed():
s1 = " outfile.write('>')\n"
else:
s1 = " outfile.write('>\\n')\n"
outfile.write(s1)
else:
if element.isMixed():
s1 = " outfile.write('<%s>' % name_)\n"
else:
s1 = " outfile.write('<%s>\\n' % name_)\n"
outfile.write(s1)
s1 = " self.exportChildren(outfile, level + 1, name_)\n"
outfile.write(s1)
s1 = " showIndent(outfile, level)\n"
outfile.write(s1)
s1 = " outfile.write('</%s>\\n' % name_)\n"
outfile.write(s1)
s1 = " def exportAttributes(self, outfile, level, name_='%s'):\n" % element.getName()
outfile.write(s1)
hasAttributes = 0
hasAttributes = generateExportAttributes(outfile, element, hasAttributes)
if base:
hasAttributes += 1
s1 = " %s.exportAttributes(self, outfile, level, name_='%s')\n" % (
base,
element.getName(),
)
outfile.write(s1)
if hasAttributes == 0:
s1 = " pass\n"
outfile.write(s1)
## if len(element.getChildren()) > 0 and not element.isMixed():
## s1 = ' showIndent(outfile, level)\n'
## outfile.write(s1)
s1 = " def exportChildren(self, outfile, level, name_='%s'):\n" % element.getName()
outfile.write(s1)
hasChildren = 0
hasChildren = generateExportChildren(outfile, element, hasChildren)
if base:
hasChildren += 1
s1 = " %s.exportChildren(self, outfile, level, name_)\n" % (base,)
outfile.write(s1)
count = countChildren(element, 0)
if count == 0:
s1 = " outfile.write(self.valueOf_)\n"
outfile.write(s1)
#
# Generate exportLiteral method.
#
def generateExportLiteralFn_1(outfile, child, name, fill):
mappedName = mapName(name)
if (
child.getType() in StringType
or child.getType() == TokenType
or child.getType() == DateTimeType
or child.getType() == DateType
):
s1 = "%s showIndent(outfile, level)\n" % fill
outfile.write(s1)
s1 = "%s outfile.write('%s=%%s,\\n' %% quote_python(self.get%s()))\n" % (
fill,
mappedName,
name.capitalize(),
)
outfile.write(s1)
elif (
child.getType() in IntegerType
or child.getType() == BooleanType
or child.getType() == PositiveIntegerType
or child.getType() == NonPositiveIntegerType
or child.getType() == NegativeIntegerType
or child.getType() == NonNegativeIntegerType
):
s1 = "%s showIndent(outfile, level)\n" % fill
outfile.write(s1)
s1 = "%s outfile.write('%s=%%d,\\n' %% self.get%s())\n" % (
fill,
mappedName,
name.capitalize(),
)
outfile.write(s1)
elif child.getType() == FloatType or child.getType() == DecimalType:
s1 = "%s showIndent(outfile, level)\n" % fill
outfile.write(s1)
s1 = "%s outfile.write('%s=%%f,\\n' %% self.get%s())\n" % (
fill,
mappedName,
name.capitalize(),
)
outfile.write(s1)
elif child.getType() == DoubleType:
s1 = "%s showIndent(outfile, level)\n" % fill
outfile.write(s1)
s1 = "%s outfile.write('%s=%%e,\\n' %% self.get%s())\n" % (
fill,
name,
name.capitalize(),
)
outfile.write(s1)
else:
s1 = "%s if self.%s:\n" % (fill, name)
outfile.write(s1)
s1 = "%s showIndent(outfile, level)\n" % fill
outfile.write(s1)
s1 = "%s outfile.write('%s=%s(\\n')\n" % (
fill,
name,
child.getType(),
)
outfile.write(s1)
if name == child.getType():
s1 = "%s self.%s.exportLiteral(outfile, level)\n" % (fill, name)
else:
s1 = "%s self.%s.exportLiteral(outfile, level, name_='%s')\n" % (
fill,
name,
name,
)
outfile.write(s1)
s1 = "%s showIndent(outfile, level)\n" % fill
outfile.write(s1)
s1 = "%s outfile.write('),\\n')\n" % (fill,)
outfile.write(s1)
def generateExportLiteralFn_2(outfile, child, name, fill):
if (
child.getType() in StringType
or child.getType() == TokenType
or child.getType() == DateTimeType
or child.getType() == DateType
):
s1 = "%s showIndent(outfile, level)\n" % fill
outfile.write(s1)
s1 = "%s outfile.write('%%s,\\n' %% quote_python(%s))\n" % (fill, name)
outfile.write(s1)
elif (
child.getType() in IntegerType
or child.getType() == BooleanType
or child.getType() == PositiveIntegerType
or child.getType() == NonPositiveIntegerType
or child.getType() == NegativeIntegerType
or child.getType() == NonNegativeIntegerType
):
s1 = "%s showIndent(outfile, level)\n" % fill
outfile.write(s1)
s1 = "%s outfile.write('%%d,\\n' %% %s)\n" % (fill, name)
outfile.write(s1)
elif child.getType() == FloatType or child.getType() == DecimalType:
s1 = "%s showIndent(outfile, level)\n" % fill
outfile.write(s1)
s1 = "%s outfile.write('%%f,\\n' %% %s)\n" % (fill, name)
outfile.write(s1)
elif child.getType() == DoubleType:
s1 = "%s showIndent(outfile, level)\n" % fill
outfile.write(s1)
s1 = "%s outfile.write('%%e,\\n' %% %s)\n" % (fill, name)
outfile.write(s1)
else:
s1 = "%s showIndent(outfile, level)\n" % fill
outfile.write(s1)
s1 = "%s outfile.write('%s(\\n')\n" % (
fill,
cleanupName(child.getType()),
)
outfile.write(s1)
if name == child.getType():
s1 = "%s %s.exportLiteral(outfile, level)\n" % (
fill,
child.getType(),
)
else:
s1 = "%s %s.exportLiteral(outfile, level, name_='%s')\n" % (
fill,
name,
name,
)
outfile.write(s1)
s1 = "%s showIndent(outfile, level)\n" % fill
outfile.write(s1)
s1 = "%s outfile.write('),\\n')\n" % (fill,)
outfile.write(s1)
def generateExportLiteralFn(outfile, prefix, element):
base = element.getBase()
s1 = " def exportLiteral(self, outfile, level, name_='%s'):\n" % element.getName()
outfile.write(s1)
s1 = " level += 1\n"
outfile.write(s1)
s1 = " self.exportLiteralAttributes(outfile, level, name_)\n"
outfile.write(s1)
s1 = " self.exportLiteralChildren(outfile, level, name_)\n"
outfile.write(s1)
s1 = " def exportLiteralAttributes(self, outfile, level, name_):\n"
outfile.write(s1)
count = 0
attrDefs = element.getAttributeDefs()
for key in attrDefs:
attrDef = attrDefs[key]
count += 1
name = attrDef.getName()
cleanName = cleanupName(name)
capName = cleanName.capitalize()
mappedName = mapName(cleanName)
s1 = " showIndent(outfile, level)\n"
outfile.write(s1)
## ipshell('(generateExportLiteral) -- Entering ipshell.\\nHit Ctrl-D to exit')
stringType = 0
data_type = attrDef.getData_type()
if data_type.find("string") >= 0:
stringType = 1
else:
stringType = 1
if stringType:
s1 = " outfile.write('%s = \"%%s\",\\n' %% (self.get%s(),))\n" % (
mappedName,
capName,
)
else:
s1 = " outfile.write('%s = %%s,\\n' %% (self.get%s(),))\n" % (
mappedName,
capName,
)
outfile.write(s1)
if element.getAnyAttribute():
count += 1
s1 = " for name, value in self.anyAttributes_.items():\n"
outfile.write(s1)
s1 = " showIndent(outfile, level)\n"
outfile.write(s1)
s1 = " outfile.write('%s = \"%s\",\\n' % (name, value,))\n"
outfile.write(s1)
if count == 0:
s1 = " pass\n"
outfile.write(s1)
if base:
s1 = " %s.exportLiteralAttributes(self, outfile, level, name_)\n" % (base,)
outfile.write(s1)
s1 = " def exportLiteralChildren(self, outfile, level, name_):\n"
outfile.write(s1)
for child in element.getChildren():
name = child.getName()
name = cleanupName(name)
# unmappedName = child.getUnmappedCleanName()
# cleanName = cleanupName(name)
# mappedName = mapName(cleanName)
if element.isMixed():
s1 = " showIndent(outfile, level)\n"
outfile.write(s1)
s1 = " outfile.write('content_ = [\\n')\n"
outfile.write(s1)
s1 = " for item_ in self.content_:\n"
outfile.write(s1)
s1 = " item_.exportLiteral(outfile, level, name_)\n"
outfile.write(s1)
s1 = " showIndent(outfile, level)\n"
outfile.write(s1)
s1 = " outfile.write('],\\n')\n"
outfile.write(s1)
else:
if child.getMaxOccurs() > 1:
s1 = " showIndent(outfile, level)\n"
outfile.write(s1)
s1 = " outfile.write('%s=[\\n')\n" % name
outfile.write(s1)
s1 = " level += 1\n"
outfile.write(s1)
s1 = " for %s in self.%s:\n" % (name, name)
outfile.write(s1)
generateExportLiteralFn_2(outfile, child, name, " ")
s1 = " level -= 1\n"
outfile.write(s1)
s1 = " showIndent(outfile, level)\n"
outfile.write(s1)
s1 = " outfile.write('],\\n')\n"
outfile.write(s1)
else:
generateExportLiteralFn_1(outfile, child, name, "")
if len(element.getChildren()) == 0:
s1 = " showIndent(outfile, level)\n"
outfile.write(s1)
s1 = " outfile.write('valueOf_ = \"%s\",\\n' % (self.valueOf_,))\n"
outfile.write(s1)
if base:
s1 = " %s.exportLiteralChildren(self, outfile, level, name_)\n" % (base,)
outfile.write(s1)
# s1 = " level -= 1\n"
# outfile.write(s1)
#
# Generate build method.
#
def generateBuildAttributes(outfile, element, hasAttributes):
attrDefs = element.getAttributeDefs()
for key in attrDefs:
attrDef = attrDefs[key]
hasAttributes += 1
name = attrDef.getName()
cleanName = cleanupName(name)
mappedName = mapName(cleanName)
atype = attrDef.getData_type()
if (
atype in IntegerType
or atype == PositiveIntegerType
or atype == NonPositiveIntegerType
or atype == NegativeIntegerType
or atype == NonNegativeIntegerType
):
s1 = " if attrs.get('%s'):\n" % name
outfile.write(s1)
s1 = " try:\n"
outfile.write(s1)
s1 = " self.%s = int(attrs.get('%s').value)\n" % (
mappedName,
name,
)
outfile.write(s1)
s1 = " except ValueError:\n"
outfile.write(s1)
s1 = " raise ValueError('Bad integer attribute (%s)')\n" % (name,)
outfile.write(s1)
if atype == PositiveIntegerType:
s1 = " if self.%s <= 0:\n" % mappedName
outfile.write(s1)
s1 = " raise ValueError('Invalid PositiveInteger (%s)')\n" % name
outfile.write(s1)
elif atype == NonPositiveIntegerType:
s1 = " if self.%s > 0:\n" % mappedName
outfile.write(s1)
s1 = " raise ValueError('Invalid NonPositiveInteger (%s)')\n" % name
outfile.write(s1)
elif atype == NegativeIntegerType:
s1 = " if self.%s >= 0:\n" % mappedName
outfile.write(s1)
s1 = " raise ValueError('Invalid NegativeInteger (%s)')\n" % name
outfile.write(s1)
elif atype == NonNegativeIntegerType:
s1 = " if self.%s < 0:\n" % mappedName
outfile.write(s1)
s1 = " raise ValueError('Invalid NonNegativeInteger (%s)')\n" % name
outfile.write(s1)
elif atype == BooleanType:
s1 = " if attrs.get('%s'):\n" % (name,)
outfile.write(s1)
s1 = " if attrs.get('%s').value in ('true', '1'):\n" % (name,)
outfile.write(s1)
s1 = " self.%s = 1\n" % (mappedName,)
outfile.write(s1)
s1 = " elif attrs.get('%s').value in ('false', '0'):\n" % (name,)
outfile.write(s1)
s1 = " self.%s = 0\n" % (mappedName,)
outfile.write(s1)
s1 = " else:\n"
outfile.write(s1)
s1 = " raise ValueError('Bad boolean attribute (%s)')\n" % (name,)
outfile.write(s1)
elif atype == FloatType or atype == DoubleType or atype == DecimalType:
s1 = " if attrs.get('%s'):\n" % (name,)
outfile.write(s1)
s1 = " try:\n"
outfile.write(s1)
s1 = " self.%s = float(attrs.get('%s').value)\n" % (
mappedName,
name,
)
outfile.write(s1)
s1 = " except:\n"
outfile.write(s1)
s1 = " raise ValueError('Bad float/double attribute (%s)')\n" % (name,)
outfile.write(s1)
elif atype == TokenType:
s1 = " if attrs.get('%s'):\n" % (name,)
outfile.write(s1)
s1 = " self.%s = attrs.get('%s').value\n" % (
mappedName,
name,
)
outfile.write(s1)
s1 = " self.%s = ' '.join(self.%s.split())\n" % (
mappedName,
mappedName,
)
outfile.write(s1)
else:
# Assume attr['type'] in StringType or attr['type'] == DateTimeType:
s1 = " if attrs.get('%s'):\n" % (name,)
outfile.write(s1)
s1 = " self.%s = attrs.get('%s').value\n" % (
mappedName,
name,
)
outfile.write(s1)
if element.getAnyAttribute():
s1 = " self.anyAttributes_ = {}\n"
outfile.write(s1)
s1 = " for name, value in attrs.items():\n"
outfile.write(s1)
s1List = [" if"]
firstTime = 1
for key in attrDefs:
if firstTime:
s1List.append(' name != "%s"' % key)
firstTime = 0
else:
s1List.append(' and name != "%s"' % key)
s1List.append(":\n")
s1 = "".join(s1List)
outfile.write(s1)
s1 = " self.anyAttributes_[name] = value\n"
outfile.write(s1)
return hasAttributes
def generateBuildMixed_1(outfile, prefix, child, headChild, keyword, delayed):
global DelayedElements, DelayedElements_subclass
nestedElements = 1
origName = child.getName()
name = child.getCleanName()
headName = cleanupName(headChild.getName())
childType = child.getType()
if (
childType in StringType
or childType == TokenType
or childType == DateTimeType
or childType == DateType
):
s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % keyword
outfile.write(s1)
s1 = " nodeName_ == '%s':\n" % origName
outfile.write(s1)
s1 = " value_ = []\n"
outfile.write(s1)
s1 = " for text_ in child_.childNodes:\n"
outfile.write(s1)
s1 = " value_.append(text_.nodeValue)\n"
outfile.write(s1)
s1 = " valuestr_ = ''.join(value_)\n"
outfile.write(s1)
if childType == TokenType:
s1 = " valuestr_ = ' '.join(valuestr_.split())\n"
outfile.write(s1)
s1 = " obj_ = self.mixedclass_(MixedContainer.CategorySimple,\n"
outfile.write(s1)
s1 = " MixedContainer.TypeString, '%s', valuestr_)\n" % origName
outfile.write(s1)
s1 = " self.content_.append(obj_)\n"
outfile.write(s1)
elif (
childType in IntegerType
or childType == PositiveIntegerType
or childType == NonPositiveIntegerType
or childType == NegativeIntegerType
or childType == NonNegativeIntegerType
):
s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % keyword
outfile.write(s1)
s1 = " nodeName_ == '%s':\n" % origName
outfile.write(s1)
s1 = " if child_.firstChild:\n"
outfile.write(s1)
s1 = " sval_ = child_.firstChild.nodeValue\n"
outfile.write(s1)
s1 = " try:\n"
outfile.write(s1)
s1 = " ival_ = int(sval_)\n"
outfile.write(s1)
s1 = " except ValueError:\n"
outfile.write(s1)
s1 = " raise ValueError('requires integer -- %s' % child_.toxml())\n"
outfile.write(s1)
if childType == PositiveIntegerType:
s1 = " if ival_ <= 0:\n"
outfile.write(s1)
s1 = " raise ValueError('Invalid positiveInteger (%s)' % child_.toxml()))\n"
outfile.write(s1)
if childType == NonPositiveIntegerType:
s1 = " if ival_ > 0:\n"
outfile.write(s1)
s1 = " raise ValueError('Invalid nonPositiveInteger (%s)' % child_.toxml()))\n"
outfile.write(s1)
if childType == NegativeIntegerType:
s1 = " if ival_ >= 0:\n"
outfile.write(s1)
s1 = " raise ValueError('Invalid negativeInteger (%s)' % child_.toxml()))\n"
outfile.write(s1)
if childType == NonNegativeIntegerType:
s1 = " if ival_ < 0:\n"
outfile.write(s1)
s1 = " raise ValueError('Invalid nonNegativeInteger (%s)' % child_.toxml()))\n"
outfile.write(s1)
s1 = " else:\n"
outfile.write(s1)
s1 = " ival_ = -1\n"
outfile.write(s1)
s1 = " obj_ = self.mixedclass_(MixedContainer.CategorySimple,\n"
outfile.write(s1)
s1 = " MixedContainer.TypeInteger, '%s', ival_)\n" % origName
outfile.write(s1)
s1 = " self.content_.append(obj_)\n"
outfile.write(s1)
elif childType == BooleanType:
s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % keyword
outfile.write(s1)
s1 = " nodeName_ == '%s':\n" % origName
outfile.write(s1)
s1 = " if child_.firstChild:\n"
outfile.write(s1)
s1 = " sval_ = child_.firstChild.nodeValue\n"
outfile.write(s1)
s1 = " if sval_ in ('true', '1'):\n"
outfile.write(s1)
s1 = " ival_ = 1\n"
outfile.write(s1)
s1 = " elif sval_ in ('false', '0'):\n"
outfile.write(s1)
s1 = " ival_ = 0\n"
outfile.write(s1)
s1 = " else:\n"
outfile.write(s1)
s1 = " raise ValueError('requires boolean -- %s' % child_.toxml())\n"
outfile.write(s1)
s1 = " obj_ = self.mixedclass_(MixedContainer.CategorySimple,\n"
outfile.write(s1)
s1 = " MixedContainer.TypeInteger, '%s', ival_)\n" % origName
outfile.write(s1)
s1 = " self.content_.append(obj_)\n"
outfile.write(s1)
elif childType == FloatType or childType == DoubleType or childType == DecimalType:
s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % keyword
outfile.write(s1)
s1 = " nodeName_ == '%s':\n" % origName
outfile.write(s1)
s1 = " if child_.firstChild:\n"
outfile.write(s1)
s1 = " sval_ = child_.firstChild.nodeValue\n"
outfile.write(s1)
s1 = " try:\n"
outfile.write(s1)
s1 = " fval_ = float(sval_)\n"
outfile.write(s1)
s1 = " except ValueError:\n"
outfile.write(s1)
s1 = " raise ValueError('requires float (or double) -- %s' % child_.toxml())\n"
outfile.write(s1)
s1 = " obj_ = self.mixedclass_(MixedContainer.CategorySimple,\n"
outfile.write(s1)
s1 = " MixedContainer.TypeFloat, '%s', fval_)\n" % origName
outfile.write(s1)
s1 = " self.content_.append(obj_)\n"
outfile.write(s1)
else:
# Perhaps it's a complexType that is defined right here.
# Generate (later) a class for the nested types.
if not delayed and not child in DelayedElements:
DelayedElements.append(child)
DelayedElements_subclass.append(child)
s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % keyword
outfile.write(s1)
s1 = " nodeName_ == '%s':\n" % origName
outfile.write(s1)
s1 = " childobj_ = %s%s.factory()\n" % (
prefix,
cleanupName(mapName(childType)),
)
outfile.write(s1)
s1 = " childobj_.build(child_)\n"
outfile.write(s1)
s1 = " obj_ = self.mixedclass_(MixedContainer.CategoryComplex,\n"
outfile.write(s1)
s1 = " MixedContainer.TypeNone, '%s', childobj_)\n" % origName
outfile.write(s1)
s1 = " self.content_.append(obj_)\n"
outfile.write(s1)
def generateBuildMixed(outfile, prefix, element, keyword, delayed, hasChildren):
for child in element.getChildren():
generateBuildMixed_1(outfile, prefix, child, child, keyword, delayed)
hasChildren += 1
keyword = "elif"
# Does this element have a substitutionGroup?
# If so generate a clause for each element in the substitutionGroup.
if child.getName() in SubstitutionGroups:
for memberName in SubstitutionGroups[child.getName()]:
if memberName in ElementDict:
member = ElementDict[memberName]
generateBuildMixed_1(outfile, prefix, member, child, keyword, delayed)
s1 = " %s child_.nodeType == Node.TEXT_NODE:\n" % keyword
outfile.write(s1)
s1 = " obj_ = self.mixedclass_(MixedContainer.CategoryText,\n"
outfile.write(s1)
s1 = " MixedContainer.TypeNone, '', child_.nodeValue)\n"
outfile.write(s1)
s1 = " self.content_.append(obj_)\n"
outfile.write(s1)
## base = element.getBase()
## if base and base in ElementDict:
## parent = ElementDict[base]
## hasChildren = generateBuildMixed(outfile, prefix, parent, keyword, delayed, hasChildren)
return hasChildren
def generateBuildStandard_1(outfile, prefix, child, headChild, keyword, delayed):
global DelayedElements, DelayedElements_subclass
origName = child.getName()
name = cleanupName(child.getName())
mappedName = mapName(name)
headName = cleanupName(headChild.getName())
attrCount = len(child.getAttributeDefs())
# dbgprint(1, '(gbs) name: %s type: %s complex: %s id: %s' % \
# (child.getName(), child.getType(), child.isComplex(), id(child), ))
childType = child.getType()
if attrCount == 0 and (
childType in StringType
or childType == TokenType
or childType == DateTimeType
or childType == DateType
):
s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % keyword
outfile.write(s1)
s1 = " nodeName_ == '%s':\n" % origName
outfile.write(s1)
s1 = " %s_ = ''\n" % name
outfile.write(s1)
s1 = " for text__content_ in child_.childNodes:\n"
outfile.write(s1)
s1 = " %s_ += text__content_.nodeValue\n" % name
outfile.write(s1)
if childType == TokenType:
s1 = " %s_ = ' '.join(%s_.split())\n" % (
name,
name,
)
outfile.write(s1)
if child.getMaxOccurs() > 1:
s1 = " self.%s.append(%s_)\n" % (
mappedName,
name,
)
outfile.write(s1)
else:
s1 = " self.%s = %s_\n" % (
mappedName,
name,
)
outfile.write(s1)
elif (
childType in IntegerType
or childType == PositiveIntegerType
or childType == NonPositiveIntegerType
or childType == NegativeIntegerType
or childType == NonNegativeIntegerType
):
s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % keyword
outfile.write(s1)
s1 = " nodeName_ == '%s':\n" % origName
outfile.write(s1)
s1 = " if child_.firstChild:\n"
outfile.write(s1)
s1 = " sval_ = child_.firstChild.nodeValue\n"
outfile.write(s1)
s1 = " try:\n"
outfile.write(s1)
s1 = " ival_ = int(sval_)\n"
outfile.write(s1)
s1 = " except ValueError:\n"
outfile.write(s1)
s1 = " raise ValueError('requires integer -- %s' % child_.toxml())\n"
outfile.write(s1)
if childType == PositiveIntegerType:
s1 = " if ival_ <= 0:\n"
outfile.write(s1)
s1 = " raise ValueError('requires positiveInteger -- %s' % child_.toxml())\n"
outfile.write(s1)
elif childType == NonPositiveIntegerType:
s1 = " if ival_ > 0:\n"
outfile.write(s1)
s1 = " raise ValueError('requires nonPositiveInteger -- %s' % child_.toxml())\n"
outfile.write(s1)
elif childType == NegativeIntegerType:
s1 = " if ival_ >= 0:\n"
outfile.write(s1)
s1 = " raise ValueError('requires negativeInteger -- %s' % child_.toxml())\n"
outfile.write(s1)
elif childType == NonNegativeIntegerType:
s1 = " if ival_ < 0:\n"
outfile.write(s1)
s1 = " raise ValueError('requires nonNegativeInteger -- %s' % child_.toxml())\n"
outfile.write(s1)
if child.getMaxOccurs() > 1:
s1 = " self.%s.append(ival_)\n" % (mappedName,)
outfile.write(s1)
else:
s1 = " self.%s = ival_\n" % (mappedName,)
outfile.write(s1)
elif childType == BooleanType:
s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % keyword
outfile.write(s1)
s1 = " nodeName_ == '%s':\n" % origName
outfile.write(s1)
s1 = " if child_.firstChild:\n"
outfile.write(s1)
s1 = " sval_ = child_.firstChild.nodeValue\n"
outfile.write(s1)
s1 = " if sval_ in ('true', '1'):\n"
outfile.write(s1)
s1 = " ival_ = 1\n"
outfile.write(s1)
s1 = " elif sval_ in ('false', '0'):\n"
outfile.write(s1)
s1 = " ival_ = 0\n"
outfile.write(s1)
s1 = " else:\n"
outfile.write(s1)
s1 = " raise ValueError('requires boolean -- %s' % child_.toxml())\n"
outfile.write(s1)
if child.getMaxOccurs() > 1:
s1 = " self.%s.append(ival_)\n" % (mappedName,)
outfile.write(s1)
else:
s1 = " self.%s = ival_\n" % (mappedName,)
outfile.write(s1)
elif childType == FloatType or childType == DoubleType or childType == DecimalType:
s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % keyword
outfile.write(s1)
s1 = " nodeName_ == '%s':\n" % origName
outfile.write(s1)
s1 = " if child_.firstChild:\n"
outfile.write(s1)
s1 = " sval_ = child_.firstChild.nodeValue\n"
outfile.write(s1)
s1 = " try:\n"
outfile.write(s1)
s1 = " fval_ = float(sval_)\n"
outfile.write(s1)
s1 = " except ValueError:\n"
outfile.write(s1)
s1 = " raise ValueError('requires float (or double) -- %s' % child_.toxml())\n"
outfile.write(s1)
if child.getMaxOccurs() > 1:
s1 = " self.%s.append(fval_)\n" % (mappedName,)
outfile.write(s1)
else:
s1 = " self.%s = fval_\n" % (mappedName,)
outfile.write(s1)
else:
# Perhaps it's a complexType that is defined right here.
# Generate (later) a class for the nested types.
if not delayed and not child in DelayedElements:
DelayedElements.append(child)
DelayedElements_subclass.append(child)
s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % keyword
outfile.write(s1)
s1 = " nodeName_ == '%s':\n" % origName
outfile.write(s1)
s1 = " obj_ = %s%s.factory()\n" % (
prefix,
cleanupName(mapName(childType)),
)
outfile.write(s1)
s1 = " obj_.build(child_)\n"
outfile.write(s1)
if headChild.getMaxOccurs() > 1:
s1 = " self.%s.append(obj_)\n" % headName
outfile.write(s1)
else:
s1 = " self.set%s(obj_)\n" % headName.capitalize()
outfile.write(s1)
def generateBuildStandard(outfile, prefix, element, keyword, delayed, hasChildren):
for child in element.getChildren():
# dbgprint(1, '(generateBuildStandard) %s type: %s' % (child.getName(), child.getType(),))
generateBuildStandard_1(outfile, prefix, child, child, keyword, delayed)
hasChildren += 1
keyword = "elif"
# Does this element have a substitutionGroup?
# If so generate a clause for each element in the substitutionGroup.
childName = child.getName()
if childName in SubstitutionGroups:
# dbgprint(1, '(BldStd) found: %s in %s' % (childName, SubstitutionGroups))
for memberName in SubstitutionGroups[childName]:
memberName = cleanupName(memberName)
if memberName in ElementDict:
member = ElementDict[memberName]
# dbgprint(1, '(BldStd) found subst: %s/%s' % (memberName, member))
generateBuildStandard_1(outfile, prefix, member, child, keyword, delayed)
return hasChildren
def generateBuildFn(outfile, prefix, element, delayed):
base = element.getBase()
outfile.write(" def build(self, node_):\n")
outfile.write(" attrs = node_.attributes\n")
outfile.write(" self.buildAttributes(attrs)\n")
## if len(element.getChildren()) > 0:
outfile.write(" for child_ in node_.childNodes:\n")
outfile.write(" nodeName_ = child_.nodeName.split(':')[-1]\n")
outfile.write(" self.buildChildren(child_, nodeName_)\n")
outfile.write(" def buildAttributes(self, attrs):\n")
hasAttributes = generateBuildAttributes(outfile, element, 0)
if base:
hasAttributes += 1
s1 = " %s.buildAttributes(self, attrs)\n" % (base,)
outfile.write(s1)
if hasAttributes == 0:
outfile.write(" pass\n")
outfile.write(" def buildChildren(self, child_, nodeName_):\n")
keyword = "if"
hasChildren = 0
if element.isMixed():
hasChildren = generateBuildMixed(outfile, prefix, element, keyword, delayed, hasChildren)
else: # not element.isMixed()
hasChildren = generateBuildStandard(outfile, prefix, element, keyword, delayed, hasChildren)
if hasChildren == 0:
s1 = " self.valueOf_ = ''\n"
outfile.write(s1)
s1 = " for child in child_.childNodes:\n"
outfile.write(s1)
s1 = " if child.nodeType == Node.TEXT_NODE:\n"
outfile.write(s1)
s1 = " self.valueOf_ += child.nodeValue\n"
outfile.write(s1)
if base and base in ElementDict:
parent = ElementDict[base]
if len(parent.getChildren()) > 0:
s1 = " %s.buildChildren(self, child_, nodeName_)\n" % (base,)
outfile.write(s1)
def countElementChildren(element, count):
count += len(element.getChildren())
base = element.getBase()
if base and base in ElementDict:
parent = ElementDict[base]
countElementChildren(parent, count)
return count
def buildCtorArgs_multilevel(element):
content = []
add = content.append
buildCtorArgs_multilevel_aux(add, element)
count = countElementChildren(element, 0)
if count == 0:
add(", valueOf_=''")
if element.isMixed():
add(", mixedclass_=None")
add(", content_=None")
s1 = "".join(content)
return s1
def buildCtorArgs_multilevel_aux(add, element):
buildCtorArgs_aux(add, element)
base = element.getBase()
if base and base in ElementDict:
parent = ElementDict[base]
buildCtorArgs_multilevel_aux(add, parent)
def buildCtorArgs_1_level(element):
content = []
add = content.append
buildCtorArgs_aux(add, element)
count = countElementChildren(element, 0)
if count == 0:
add(", valueOf_=''")
s1 = "".join(content)
return s1
def buildCtorArgs_aux(add, element):
attrDefs = element.getAttributeDefs()
for key in attrDefs:
attrDef = attrDefs[key]
name = attrDef.getName()
mappedName = name.replace(":", "_")
mappedName = cleanupName(mapName(mappedName))
try:
atype = attrDef.getData_type()
except KeyError:
atype = StringType
if atype in StringType or atype == TokenType or atype == DateTimeType or atype == DateType:
add(", %s=''" % mappedName)
elif atype in IntegerType:
add(", %s=-1" % mappedName)
elif atype == PositiveIntegerType:
add(", %s=1" % mappedName)
elif atype == NonPositiveIntegerType:
add(", %s=0" % mappedName)
elif atype == NegativeIntegerType:
add(", %s=-1" % mappedName)
elif atype == NonNegativeIntegerType:
add(", %s=0" % mappedName)
elif atype == BooleanType:
add(", %s=0" % mappedName)
elif atype == FloatType or atype == DoubleType or atype == DecimalType:
add(", %s=0.0" % mappedName)
else:
add(", %s=None" % mappedName)
nestedElements = 0
for child in element.getChildren():
nestedElements = 1
if child.getMaxOccurs() > 1:
add(", %s=None" % child.getCleanName())
else:
childType = child.getType()
if (
childType in StringType
or childType == TokenType
or childType == DateTimeType
or childType == DateType
):
add(", %s=''" % child.getCleanName())
elif childType in IntegerType:
add(", %s=-1" % child.getCleanName())
elif childType == PositiveIntegerType:
add(", %s=1" % child.getCleanName())
elif childType == NonPositiveIntegerType:
add(", %s=0" % child.getCleanName())
elif childType == NegativeIntegerType:
add(", %s=-1" % child.getCleanName())
elif childType == NonNegativeIntegerType:
add(", %s=0" % child.getCleanName())
elif childType == BooleanType:
add(", %s=0" % child.getCleanName())
elif childType == FloatType or childType == DoubleType or childType == DecimalType:
add(", %s=0.0" % child.getCleanName())
else:
add(", %s=None" % child.getCleanName())
MixedCtorInitializers = """\
if mixedclass_ is None:
self.mixedclass_ = MixedContainer
else:
self.mixedclass_ = mixedclass_
if content_ is None:
self.content_ = []
else:
self.content_ = content_
"""
def generateCtor(outfile, element):
s2 = buildCtorArgs_multilevel(element)
s1 = " def __init__(self%s):\n" % s2
outfile.write(s1)
base = element.getBase()
if base and base in ElementDict:
parent = ElementDict[base]
s2 = buildCtorParams(parent)
s1 = " %s.__init__(self%s)\n" % (
base,
s2,
)
outfile.write(s1)
attrDefs = element.getAttributeDefs()
for key in attrDefs:
attrDef = attrDefs[key]
mappedName = cleanupName(attrDef.getName())
mappedName = mapName(mappedName)
s1 = " self.%s = %s\n" % (mappedName, mappedName)
outfile.write(s1)
member = 1
# Generate member initializers in ctor.
if element.isMixed():
outfile.write(MixedCtorInitializers)
else:
member = 0
nestedElements = 0
for child in element.getChildren():
name = cleanupName(child.getCleanName())
if child.getMaxOccurs() > 1:
s1 = " if %s is None:\n" % (name,)
outfile.write(s1)
s1 = " self.%s = []\n" % (name,)
outfile.write(s1)
s1 = " else:\n"
outfile.write(s1)
s1 = " self.%s = %s\n" % (name, name)
outfile.write(s1)
else:
s1 = " self.%s = %s\n" % (name, name)
outfile.write(s1)
member = 1
nestedElements = 1
if not nestedElements:
s1 = " self.valueOf_ = valueOf_\n"
outfile.write(s1)
member = 1
if element.getAnyAttribute():
s1 = " self.anyAttributes_ = {}\n"
outfile.write(s1)
member = 1
if not member:
outfile.write(" pass\n")
# Generate get/set/add member functions.
def generateGettersAndSetters(outfile, element):
nestedElements = 0
for child in element.getChildren():
nestedElements = 1
name = cleanupName(child.getCleanName())
unmappedName = cleanupName(child.getName())
capName = unmappedName.capitalize()
s1 = " def get%s(self): return self.%s\n" % (capName, name)
outfile.write(s1)
s1 = " def set%s(self, %s): self.%s = %s\n" % (capName, name, name, name)
outfile.write(s1)
if child.getMaxOccurs() > 1:
s1 = " def add%s(self, value): self.%s.append(value)\n" % (capName, name)
outfile.write(s1)
s1 = " def insert%s(self, index, value): self.%s[index] = value\n" % (
capName,
name,
)
outfile.write(s1)
if GenerateProperties:
s1 = " %sProp = property(get%s, set%s)\n" % (
unmappedName,
capName,
capName,
)
outfile.write(s1)
attrDefs = element.getAttributeDefs()
for key in attrDefs:
attrDef = attrDefs[key]
name = cleanupName(attrDef.getName().replace(":", "_"))
mappedName = mapName(name)
capName = mappedName.capitalize()
s1 = " def get%s(self): return self.%s\n" % (name.capitalize(), mappedName)
outfile.write(s1)
#
# What? An attribute cannot occur multiple times on the same
# element. No attribute is a list of values. Right?
## if element.getMaxOccurs() > 1:
## s1 = ' def add%s(self, %s): self.%s.append(%s)\n' % \
## (capName, mappedName, mappedName, mappedName)
## outfile.write(s1)
## s1 = ' def set%s(self, %s, index): self.%s[index] = %s\n' % \
## (name.capitalize(), mappedName, mappedName, mappedName)
## outfile.write(s1)
## else:
s1 = " def set%s(self, %s): self.%s = %s\n" % (
name.capitalize(),
mappedName,
mappedName,
mappedName,
)
outfile.write(s1)
if GenerateProperties:
s1 = " %sProp = property(get%s, set%s)\n" % (
mappedName,
capName,
capName,
)
outfile.write(s1)
if not nestedElements:
s1 = " def getValueOf_(self): return self.valueOf_\n"
outfile.write(s1)
s1 = " def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_\n"
outfile.write(s1)
if element.getAnyAttribute():
s1 = " def getAnyAttributes_(self): return self.anyAttributes_\n"
outfile.write(s1)
s1 = " def setAnyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_\n"
outfile.write(s1)
def generateClasses(outfile, prefix, element, delayed):
base = element.getBase()
wrt = outfile.write
if (not element.getChildren()) and (not element.getAttributeDefs()):
return
# If this element is an extension (has a base) and the base has
# not been generated, then postpone it.
if base and base in ElementDict:
parent = ElementDict[base]
parentName = parent.getName()
if parentName not in AlreadyGenerated:
PostponedExtensions.append(element)
return
if element.getName() in AlreadyGenerated:
return
AlreadyGenerated.append(element.getName())
if element.getMixedExtensionError():
print(
"*** Element %s extension chain contains mixed and non-mixed content. Not generated."
% (element.getName(),)
)
return
ElementsForSubclasses.append(element)
name = element.getCleanName()
if GenerateProperties:
if base:
s1 = "class %s%s(object, %s):\n" % (prefix, name, base)
else:
s1 = "class %s%s(object):\n" % (prefix, name)
else:
if base:
s1 = "class %s%s(%s):\n" % (prefix, name, base)
else:
s1 = "class %s%s:\n" % (prefix, name)
wrt(s1)
wrt(" subclass = None\n")
generateCtor(outfile, element)
wrt(" def factory(*args_, **kwargs_):\n")
wrt(" if %s%s.subclass:\n" % (prefix, name))
wrt(" return %s%s.subclass(*args_, **kwargs_)\n" % (prefix, name))
wrt(" else:\n")
wrt(" return %s%s(*args_, **kwargs_)\n" % (prefix, name))
wrt(" factory = staticmethod(factory)\n")
generateGettersAndSetters(outfile, element)
generateExportFn(outfile, prefix, element)
generateExportLiteralFn(outfile, prefix, element)
generateBuildFn(outfile, prefix, element, delayed)
wrt("# end class %s\n" % name)
wrt("\n\n")
#
# Generate the SAX handler class for SAX parsing.
#
SAX_STARTELEMENT_1 = """\
def startElement(self, name, attrs):
done = 0
if name == '%s':
obj = %s.factory()
stackObj = SaxStackElement('%s', obj)
self.stack.append(stackObj)
done = 1
"""
SAX_STARTELEMENT_2 = """\
stackObj = SaxStackElement('%s', obj)
self.stack.append(stackObj)
done = 1
"""
SAX_STARTELEMENT_3 = """\
stackObj = SaxStackElement('%s', None)
self.stack.append(stackObj)
done = 1
"""
SAX_STARTELEMENT_4 = """\
if not done:
self.reportError('"%s" element not allowed here.' % name)
"""
SAX_ATTR_INTEGER = """\
val = attrs.get('%s', None)
if val is not None:
try:
obj.set%s(int(val))
except:
self.reportError('"%s" attribute must be integer')
"""
SAX_ATTR_BOOLEAN = """\
val = attrs.get('%s', None)
if val is not None:
if val in ('true', '1'):
obj.set%s(1)
elif val in ('false', '0'):
obj.set%s(0)
else:
self.reportError('"%s" attribute must be boolean ("true", "1", "false", "0")')
"""
SAX_ATTR_FLOAT = """\
val = attrs.get('%s', None)
if val is not None:
try:
obj.set%s(float(val))
except:
self.reportError('"%s" attribute must be float')
"""
SAX_ATTR_STRING = """\
val = attrs.get('%s', None)
if val is not None:
obj.set%s(val)
"""
def getClassName(element):
name = element.getCleanName()
return name
def generateSaxAttributes(wrt, element):
attrDefs = element.getAttributeDefs()
for key in attrDefs:
attrDef = attrDefs[key]
name = attrDef.getName()
atype = attrDef.getData_type()
if atype in IntegerType:
s1 = SAX_ATTR_INTEGER % (name, name.capitalize(), name)
wrt(s1)
## s1 = " if attrs.get('%s'):\n" % name
## wrt(s1)
## s1 = ' try:\n'
## wrt(s1)
## s1 = " self.%s = int(attrs.get('%s').value)\n" % \
## (name, name)
## wrt(s1)
## s1 = ' except ValueError:\n'
## wrt(s1)
## s1 = " raise ValueError('Bad integer')\n"
## wrt(s1)
elif atype == BooleanType:
s1 = SAX_ATTR_BOOLEAN % (name, name.capitalize(), name.capitalize(), name)
wrt(s1)
## wrt(s1)
## s1 = " if attrs.get('%s'):\n" % name
## wrt(s1)
## s1 = " if attrs.get('%s').value in ('true', '1'):\n" % \
## name
## wrt(s1)
## s1 = " self.%s = 1\n" % \
## name
## wrt(s1)
## s1 = " elif attrs.get('%s').value in ('false', '0'):\n" % \
## name
## wrt(s1)
## s1 = " self.%s = 0\n" % \
## name
## wrt(s1)
## s1 = ' else:\n'
## wrt(s1)
## s1 = " raise ValueError('Bad boolean')\n"
## wrt(s1)
elif atype == FloatType or atype == DoubleType or atype == DecimalType:
s1 = SAX_ATTR_FLOAT % (name, name.capitalize(), name)
wrt(s1)
## s1 = " if attrs.get('%s'):\n" % name
## wrt(s1)
## s1 = ' try:\n'
## wrt(s1)
## s1 = " self.%s = float(attrs.get('%s').value)\n" % \
## (name, name)
## wrt(s1)
## s1 = ' except:\n'
## wrt(s1)
## s1 = " raise ValueError('Bad float/double')\n"
## wrt(s1)
else:
# Assume attr['type'] in StringType or attr['type'] == DateTimeType:
s1 = SAX_ATTR_STRING % (name, name.capitalize())
wrt(s1)
## s1 = " if attrs.get('%s'):\n" % name
## wrt(s1)
## s1 = " self.%s = attrs.get('%s').value\n" % (name, name)
## wrt(s1)
def generateSAXStartElement_1(wrt, element):
origName = element.getName()
typeName = cleanupName(mapName(element.getRawType()))
className = element.getCleanName()
s1 = " elif name == '%s':\n" % origName
wrt(s1)
if element.isComplex():
s1 = " obj = %s.factory()\n" % cleanupName(typeName)
wrt(s1)
element1 = SaxElementDict[element.getCleanName()]
generateSaxAttributes(wrt, element1)
if element.isComplex():
s1 = SAX_STARTELEMENT_2 % className
else:
s1 = SAX_STARTELEMENT_3 % className
wrt(s1)
def generateSAXStartElement(outfile, root, elementList):
wrt = outfile.write
name = root.getChildren()[0].getName()
s1 = SAX_STARTELEMENT_1 % (name, name, name)
wrt(s1)
for element, parent in elementList:
generateSAXStartElement_1(wrt, element)
s1 = SAX_STARTELEMENT_4
wrt(s1)
wrt("\n")
SAX_ENDELEMENT_1 = """\
if name == '%s':
if len(self.stack) == 1:
self.root = self.stack[-1].obj
self.stack.pop()
done = 1
"""
SAX_ENDELEMENT_2 = """\
elif name == '%s':
if len(self.stack) >= 2:
self.stack[-2].obj.%s%s(self.stack[-1].obj)
self.stack.pop()
done = 1
"""
SAX_ENDELEMENT_3 = """\
elif name == '%s':
if len(self.stack) >= 2:
content = self.stack[-1].content
%s self.stack[-2].obj.%s%s(content)
self.stack.pop()
done = 1
"""
SAX_ENDELEMENT_INT = """\
if content:
try:
content = int(content)
except:
self.reportError('"%s" must be integer -- content: %%s' %% content)
else:
content = -1
"""
SAX_ENDELEMENT_FLOAT = """\
if content:
try:
content = float(content)
except:
self.reportError('"%s" must be float -- content: %%s' %% content)
else:
content = -1
"""
SAX_ENDELEMENT_BOOLEAN = """\
if content and content in ('true', '1'):
content = 1
else:
content = 0
"""
SAX_ENDELEMENT_4 = """\
if not done:
self.reportError('"%s" element not allowed here.' % name)
"""
def generateParentCheck(parent):
s1 = "self.stack[-2].name == '%s'" % getClassName(parent)
return s1
## strList = []
## for parent in parentList:
## strList.append("self.stack[-2].name == '%s'" % \
## parent.getName())
## s1 = ' or '.join(strList)
## if len(parentList) > 1:
## s1 = '(%s)' % s1
## return s1
def generateSAXEndElement(outfile, root, elementList):
wrt = outfile.write
s1 = " def endElement(self, name):\n"
wrt(s1)
s1 = " done = 0\n"
wrt(s1)
name = root.getChildren()[0].getName()
s1 = SAX_ENDELEMENT_1 % (name,)
wrt(s1)
for element, parent in elementList:
# s2 = generateParentCheck(parent)
name = element.getName()
capName = element.getUnmappedCleanName().capitalize()
if element.isComplex():
if element.getMaxOccurs() > 1:
s1 = SAX_ENDELEMENT_2 % (name, "add", capName)
else:
s1 = SAX_ENDELEMENT_2 % (name, "set", capName)
else:
etype = element.getType()
if etype in IntegerType:
s3 = SAX_ENDELEMENT_INT % name
elif etype == FloatType or etype == DoubleType or etype == DecimalType:
s3 = SAX_ENDELEMENT_FLOAT % name
elif etype == BooleanType:
s3 = SAX_ENDELEMENT_BOOLEAN
else:
s3 = ""
if element.getMaxOccurs() > 1:
s1 = SAX_ENDELEMENT_3 % (name, s3, "add", capName)
else:
s1 = SAX_ENDELEMENT_3 % (name, s3, "set", capName)
wrt(s1)
s1 = SAX_ENDELEMENT_4
wrt(s1)
wrt("\n")
SAX_HEADER = """\
from xml.sax import handler, make_parser
class SaxStackElement:
def __init__(self, name='', obj=None):
self.name = name
self.obj = obj
self.content = ''
#
# SAX handler
#
class Sax%sHandler(handler.ContentHandler):
def __init__(self):
self.stack = []
self.root = None
def getRoot(self):
return self.root
def setDocumentLocator(self, locator):
self.locator = locator
def showError(self, msg):
print('*** (showError):', msg)
sys.exit(-1)
"""
SAX_FOOTER = """\
def characters(self, chrs, start, end):
if len(self.stack) > 0:
self.stack[-1].content += chrs[start:end]
def reportError(self, mesg):
locator = self.locator
sys.stderr.write('Doc: %s Line: %d Column: %d\\n' % \\
(locator.getSystemId(), locator.getLineNumber(),
locator.getColumnNumber() + 1))
sys.stderr.write(mesg)
sys.stderr.write('\\n')
sys.exit(-1)
#raise RuntimeError
"""
##def produceAllElements(element, parent):
## if element.getType() in StringType or \
## element.getType() in IntegerType or \
## element.getType() == DecimalType or \
## element.getType() == FloatType or \
## element.getType() == DoubleType or \
## element.getType() == BooleanType or \
## len(element.getChildren()) != 0:
## yield (element, parent)
## for child in element.getChildren():
## for element1, parent1 in produceAllElements(child, element):
## yield (element1, parent1)
#
# This version of produceAllElements does not use 'yield' and is,
# therefore, usable with older versions of Python.
def produceAllElements_nogen(element, parent, collection):
collection.append((element, parent))
for child in element.getChildren():
produceAllElements_nogen(child, element, collection)
def generateSAXHndlr(outfile, root):
firstElement = root.getChildren()[0]
name = firstElement.getName()
s1 = SAX_HEADER % cleanupName(name.capitalize())
outfile.write(s1)
elementList = []
collection = []
produceAllElements_nogen(root, None, collection)
for element, parent in collection:
if element == root:
continue
elementList.append((element, parent))
## print '(gsh) element: %s/%s/%d parent: %s/%s/%d' % \
## (element.getUnmappedCleanName(), element.getType(), id(element),
## #(element.getName(), element.getType(), id(element),
## parent.getName(), parent.getType(), id(parent))
## if parent.getName() == 'booster':
## ipshell('at booster -- Entering ipshell.\\nHit Ctrl-D to exit')
## if element in elementDict:
## elementDict[element].append(parent)
## else:
## elementDict[element] = [parent]
elementList1 = []
alreadySeen = []
for element, parent in elementList:
if parent == root:
continue
if element.getName() in alreadySeen:
continue
alreadySeen.append(element.getName())
elementList1.append((element, parent))
## print '+' * 20
## for element, parent in elementList1:
## print '(gsh) element: %s/%s/%d parent: %s/%s/%d' % \
## (element.getUnmappedCleanName(), element.getType(), id(element),
## #(element.getName(), element.getType(), id(element),
## parent.getName(), parent.getType(), id(parent))
generateSAXStartElement(outfile, root, elementList1)
generateSAXEndElement(outfile, root, elementList1)
s1 = SAX_FOOTER
outfile.write(s1)
def collect(element, elements):
if element.getName() != "root":
elements.append(element)
for child in element.getChildren():
collect(child, elements)
TEMPLATE_HEADER = """\
#!/usr/bin/env python3
#
# Generated %s by generateDS.py.
# Update it with: python generateDS.py -o generateModel_Module.py generateMetaModel_Module.xsd
#
# WARNING! All changes made in this file will be lost!
#
import sys
import getopt
from xml.dom import minidom
from xml.dom import Node
#
# If you have installed IPython you can uncomment and use the following.
# IPython is available from http://ipython.scipy.org/.
#
## from IPython.Shell import IPShellEmbed
## args = ''
## ipshell = IPShellEmbed(args,
## banner = 'Dropping into IPython',
## exit_msg = 'Leaving Interpreter, back to program.')
# Then use the following line where and when you want to drop into the
# IPython shell:
# ipshell('<some message> -- Entering ipshell.\\nHit Ctrl-D to exit')
#
# Support/utility functions.
#
def showIndent(outfile, level):
for idx in range(level):
outfile.write(' ')
def quote_xml(inStr):
s1 = inStr
s1 = s1.replace('&', '&')
s1 = s1.replace('<', '<')
s1 = s1.replace('"', '"')
return s1
def quote_python(inStr):
s1 = inStr
if s1.find("'") == -1:
if s1.find('\\n') == -1:
return "'%%s'" %% s1
else:
return "'''%%s'''" %% s1
else:
if s1.find('"') != -1:
s1 = s1.replace('"', '\\\\"')
if s1.find('\\n') == -1:
return '"%%s"' %% s1
else:
return '\"\"\"%%s\"\"\"' %% s1
class MixedContainer:
# Constants for category:
CategoryNone = 0
CategoryText = 1
CategorySimple = 2
CategoryComplex = 3
# Constants for content_type:
TypeNone = 0
TypeText = 1
TypeString = 2
TypeInteger = 3
TypeFloat = 4
TypeDecimal = 5
TypeDouble = 6
TypeBoolean = 7
def __init__(self, category, content_type, name, value):
self.category = category
self.content_type = content_type
self.name = name
self.value = value
def getCategory(self):
return self.category
def getContenttype(self, content_type):
return self.content_type
def getValue(self):
return self.value
def getName(self):
return self.name
def export(self, outfile, level, name):
if self.category == MixedContainer.CategoryText:
outfile.write(self.value)
elif self.category == MixedContainer.CategorySimple:
self.exportSimple(outfile, level, name)
else: # category == MixedContainer.CategoryComplex
self.value.export(outfile, level, name)
def exportSimple(self, outfile, level, name):
if self.content_type == MixedContainer.TypeString:
outfile.write('<%%s>%%s</%%s>' %% (self.name, self.value, self.name))
elif self.content_type == MixedContainer.TypeInteger or \\
self.content_type == MixedContainer.TypeBoolean:
outfile.write('<%%s>%%d</%%s>' %% (self.name, self.value, self.name))
elif self.content_type == MixedContainer.TypeFloat or \\
self.content_type == MixedContainer.TypeDecimal:
outfile.write('<%%s>%%f</%%s>' %% (self.name, self.value, self.name))
elif self.content_type == MixedContainer.TypeDouble:
outfile.write('<%%s>%%g</%%s>' %% (self.name, self.value, self.name))
def exportLiteral(self, outfile, level, name):
if self.category == MixedContainer.CategoryText:
showIndent(outfile, level)
outfile.write('MixedContainer(%%d, %%d, "%%s", "%%s"),\\n' %% \\
(self.category, self.content_type, self.name, self.value))
elif self.category == MixedContainer.CategorySimple:
showIndent(outfile, level)
outfile.write('MixedContainer(%%d, %%d, "%%s", "%%s"),\\n' %% \\
(self.category, self.content_type, self.name, self.value))
else: # category == MixedContainer.CategoryComplex
showIndent(outfile, level)
outfile.write('MixedContainer(%%d, %%d, "%%s",\\n' %% \\
(self.category, self.content_type, self.name,))
self.value.exportLiteral(outfile, level + 1)
showIndent(outfile, level)
outfile.write(')\\n')
#
# Data representation classes.
#
"""
# Fool (and straighten out) the syntax highlighting.
# DUMMY = '''
def generateHeader(outfile, prefix):
s1 = TEMPLATE_HEADER % time.ctime()
outfile.write(s1)
TEMPLATE_MAIN = """\
USAGE_TEXT = \"\"\"
Usage: python <%(prefix)sParser>.py [ -s ] <in_xml_file>
Options:
-s Use the SAX parser, not the minidom parser.
\"\"\"
def usage():
print(USAGE_TEXT)
sys.exit(-1)
#
# SAX handler used to determine the top level element.
#
class SaxSelectorHandler(handler.ContentHandler):
def __init__(self):
self.topElementName = None
def getTopElementName(self):
return self.topElementName
def startElement(self, name, attrs):
self.topElementName = name
raise StopIteration
def parseSelect(inFileName):
infile = open(inFileName, 'r')
topElementName = None
parser = make_parser()
documentHandler = SaxSelectorHandler()
parser.setContentHandler(documentHandler)
try:
try:
parser.parse(infile)
except StopIteration:
topElementName = documentHandler.getTopElementName()
if topElementName is None:
raise RuntimeError('no top level element')
topElementName = topElementName.replace('-', '_').replace(':', '_')
if topElementName not in globals():
raise RuntimeError('no class for top element: %%s' %% topElementName)
topElement = globals()[topElementName]
infile.seek(0)
doc = minidom.parse(infile)
finally:
infile.close()
rootNode = doc.childNodes[0]
rootObj = topElement.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
doc = None
sys.stdout.write('<?xml version="1.0" ?>\\n')
rootObj.export(sys.stdout, 0)
return rootObj
def saxParse(inFileName):
parser = make_parser()
documentHandler = Sax%(cap_name)sHandler()
parser.setDocumentHandler(documentHandler)
parser.parse('file:%%s' %% inFileName)
root = documentHandler.getRoot()
sys.stdout.write('<?xml version="1.0" ?>\\n')
root.export(sys.stdout, 0)
return root
def saxParseString(inString):
parser = make_parser()
documentHandler = Sax%(cap_name)sHandler()
parser.setDocumentHandler(documentHandler)
parser.feed(inString)
parser.close()
rootObj = documentHandler.getRoot()
#sys.stdout.write('<?xml version="1.0" ?>\\n')
#rootObj.export(sys.stdout, 0)
return rootObj
def parse(inFileName):
doc = minidom.parse(inFileName)
rootNode = doc.documentElement
rootObj = %(prefix)s%(root)s.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
doc = None
sys.stdout.write('<?xml version="1.0" ?>\\n')
rootObj.export(sys.stdout, 0, name_="%(name)s")
return rootObj
def parseString(inString):
doc = minidom.parseString(inString)
rootNode = doc.documentElement
rootObj = %(prefix)s%(root)s.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
doc = None
sys.stdout.write('<?xml version="1.0" ?>\\n')
rootObj.export(sys.stdout, 0, name_="%(name)s")
return rootObj
def parseLiteral(inFileName):
doc = minidom.parse(inFileName)
rootNode = doc.documentElement
rootObj = %(prefix)s%(root)s.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
doc = None
sys.stdout.write('from %(module_name)s import *\\n\\n')
sys.stdout.write('rootObj = %(name)s(\\n')
rootObj.exportLiteral(sys.stdout, 0, name_="%(name)s")
sys.stdout.write(')\\n')
return rootObj
def main():
args = sys.argv[1:]
if len(args) == 2 and args[0] == '-s':
saxParse(args[1])
elif len(args) == 1:
parse(args[0])
else:
usage()
if __name__ == '__main__':
main()
#import pdb
#pdb.run('main()')
"""
# Fool (and straighten out) the syntax highlighting.
# DUMMY = '''
def generateMain(outfile, prefix, root):
name = root.getChildren()[0].getName()
elType = cleanupName(root.getChildren()[0].getType())
if RootElement:
rootElement = RootElement
else:
rootElement = elType
params = {
"prefix": prefix,
"cap_name": cleanupName(name.capitalize()),
"name": cleanupName(name),
"module_name": os.path.splitext(os.path.basename(outfile.name))[0],
"root": rootElement,
}
s1 = TEMPLATE_MAIN % params
outfile.write(s1)
def buildCtorParams(element):
content = []
add = content.append
if element.isMixed():
add(", mixedclass_")
add(", content_")
else:
buildCtorParams_aux(add, element)
s1 = "".join(content)
return s1
def buildCtorParams_aux(add, element):
attrDefs = element.getAttributeDefs()
for key in attrDefs:
attrDef = attrDefs[key]
name = attrDef.getName()
cleanName = cleanupName(mapName(name))
add(", %s" % cleanName)
for child in element.getChildren():
add(", %s" % child.getCleanName())
base = element.getBase()
if base and base in ElementDict:
parent = ElementDict[base]
buildCtorParams_aux(add, parent)
def get_class_behavior_args(classBehavior):
argList = []
args = classBehavior.getArgs()
args = args.getArg()
# print '(get_class_behavior_args) args:', args
for arg in args:
argList.append(arg.getName())
argString = ", ".join(argList)
return argString
#
# Retrieve the implementation body via an HTTP request to a
# URL formed from the concatenation of the baseImplUrl and the
# implUrl.
# An alternative implementation of get_impl_body() that also
# looks in the local file system is commented out below.
#
def get_impl_body(classBehavior, baseImplUrl, implUrl):
impl = " pass\n"
if implUrl:
if baseImplUrl:
implUrl = "%s%s" % (baseImplUrl, implUrl)
try:
implFile = urlopen(implUrl)
impl = implFile.read()
implFile.close()
except HTTPError:
print("*** Implementation at %s not found." % implUrl)
return impl
###
### This alternative implementation of get_impl_body() tries the URL
### via http first, then, if that fails, looks in a directory on
### the local file system (baseImplUrl) for a file (implUrl)
### containing the implementation body.
###
##def get_impl_body(classBehavior, baseImplUrl, implUrl):
## impl = ' pass\n'
## if implUrl:
## trylocal = 0
## if baseImplUrl:
## implUrl = '%s%s' % (baseImplUrl, implUrl)
## try:
## implFile = urlopen(implUrl)
## impl = implFile.read()
## implFile.close()
## except:
## trylocal = 1
## if trylocal:
## try:
## implFile = open(implUrl)
## impl = implFile.read()
## implFile.close()
## except:
## print ('*** Implementation at %s not found.' % implUrl)
## return impl
def generateClassBehaviors(wrt, classBehaviors, baseImplUrl):
for classBehavior in classBehaviors:
behaviorName = classBehavior.getName()
#
# Generate the core behavior.
argString = get_class_behavior_args(classBehavior)
if argString:
wrt(" def %s(self, %s, *args):\n" % (behaviorName, argString))
else:
wrt(" def %s(self, *args):\n" % (behaviorName,))
implUrl = classBehavior.getImpl_url()
impl = get_impl_body(classBehavior, baseImplUrl, implUrl)
wrt(impl)
wrt("\n")
#
# Generate the ancillaries for this behavior.
ancillaries = classBehavior.getAncillaries()
if ancillaries:
ancillaries = ancillaries.getAncillary()
if ancillaries:
for ancillary in ancillaries:
argString = get_class_behavior_args(ancillary)
if argString:
wrt(" def %s(self, %s, *args):\n" % (ancillary.getName(), argString))
else:
wrt(" def %s(self, *args):\n" % (ancillary.getName(),))
implUrl = ancillary.getImpl_url()
impl = get_impl_body(classBehavior, baseImplUrl, implUrl)
wrt(impl)
wrt("\n")
#
# Generate the wrapper method that calls the ancillaries and
# the core behavior.
argString = get_class_behavior_args(classBehavior)
if argString:
wrt(" def %s_wrapper(self, %s, *args):\n" % (behaviorName, argString))
else:
wrt(" def %s_wrapper(self, *args):\n" % (behaviorName,))
if ancillaries:
for ancillary in ancillaries:
role = ancillary.getRole()
if role == "DBC-precondition":
wrt(" if not self.%s(*args)\n" % (ancillary.getName(),))
wrt(" return False\n")
if argString:
wrt(" result = self.%s(%s, *args)\n" % (behaviorName, argString))
else:
wrt(" result = self.%s(*args)\n" % (behaviorName,))
if ancillaries:
for ancillary in ancillaries:
role = ancillary.getRole()
if role == "DBC-postcondition":
wrt(" if not self.%s(*args)\n" % (ancillary.getName(),))
wrt(" return False\n")
wrt(" return result\n")
wrt("\n")
def generateSubclass(outfile, element, prefix, xmlbehavior, behaviors, baseUrl):
wrt = outfile.write
if not element.isComplex():
return
if (not element.getChildren()) and (not element.getAttributeDefs()):
return
if element.getName() in AlreadyGenerated_subclass:
return
AlreadyGenerated_subclass.append(element.getName())
name = element.getCleanName()
wrt("class %s%s%s(supermod.%s):\n" % (prefix, name, SubclassSuffix, name))
s1 = buildCtorArgs_multilevel(element)
wrt(" def __init__(self%s):\n" % s1)
s1 = buildCtorParams(element)
wrt(" supermod.%s%s.__init__(self%s)\n" % (prefix, name, s1))
if xmlbehavior and behaviors:
wrt("\n")
wrt(" #\n")
wrt(" # XMLBehaviors\n")
wrt(" #\n")
# Get a list of behaviors for this class/subclass.
classDictionary = behaviors.get_class_dictionary()
if name in classDictionary:
classBehaviors = classDictionary[name]
else:
classBehaviors = None
if classBehaviors:
generateClassBehaviors(wrt, classBehaviors, baseUrl)
wrt("supermod.%s.subclass = %s%s\n" % (name, name, SubclassSuffix))
wrt("# end class %s%s%s\n" % (prefix, name, SubclassSuffix))
wrt("\n\n")
TEMPLATE_SUBCLASS_HEADER = """\
#!/usr/bin/env python
#
# Generated %s by generateDS.py.
#
import sys
from xml.dom import minidom
from xml.sax import handler, make_parser
import %s as supermod
"""
TEMPLATE_SUBCLASS_FOOTER = """\
#
# SAX handler used to determine the top level element.
#
class SaxSelectorHandler(handler.ContentHandler):
def __init__(self):
self.topElementName = None
def getTopElementName(self):
return self.topElementName
def startElement(self, name, attrs):
self.topElementName = name
raise StopIteration
def parseSelect(inFileName):
infile = open(inFileName, 'r')
topElementName = None
parser = make_parser()
documentHandler = SaxSelectorHandler()
parser.setContentHandler(documentHandler)
try:
try:
parser.parse(infile)
except StopIteration:
topElementName = documentHandler.getTopElementName()
if topElementName is None:
raise RuntimeError, 'no top level element'
topElementName = topElementName.replace('-', '_').replace(':', '_')
if topElementName not in supermod.__dict__:
raise RuntimeError, 'no class for top element: %%s' %% topElementName
topElement = supermod.__dict__[topElementName]
infile.seek(0)
doc = minidom.parse(infile)
finally:
infile.close()
rootNode = doc.childNodes[0]
rootObj = topElement.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
doc = None
sys.stdout.write('<?xml version="1.0" ?>\\n')
rootObj.export(sys.stdout, 0)
return rootObj
def saxParse(inFileName):
parser = make_parser()
documentHandler = supermod.Sax%(cap_name)sHandler()
parser.setDocumentHandler(documentHandler)
parser.parse('file:%%s' %% inFileName)
rootObj = documentHandler.getRoot()
#sys.stdout.write('<?xml version="1.0" ?>\\n')
#rootObj.export(sys.stdout, 0)
return rootObj
def saxParseString(inString):
parser = make_parser()
documentHandler = supermod.SaxContentHandler()
parser.setDocumentHandler(documentHandler)
parser.feed(inString)
parser.close()
rootObj = documentHandler.getRoot()
#sys.stdout.write('<?xml version="1.0" ?>\\n')
#rootObj.export(sys.stdout, 0)
return rootObj
def parse(inFilename):
doc = minidom.parse(inFilename)
rootNode = doc.documentElement
rootObj = supermod.%(root)s.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
doc = None
sys.stdout.write('<?xml version="1.0" ?>\\n')
rootObj.export(sys.stdout, 0, name_="%(name)s")
doc = None
return rootObj
def parseString(inString):
doc = minidom.parseString(inString)
rootNode = doc.documentElement
rootObj = supermod.%(root)s.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
doc = None
sys.stdout.write('<?xml version="1.0" ?>\\n')
rootObj.export(sys.stdout, 0, name_="%(name)s")
return rootObj
def parseLiteral(inFilename):
doc = minidom.parse(inFilename)
rootNode = doc.documentElement
rootObj = supermod.%(root)s.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
doc = None
sys.stdout.write('from %(super)s import *\\n\\n')
sys.stdout.write('rootObj = %(name)s(\\n')
rootObj.exportLiteral(sys.stdout, 0, name_="%(name)s")
sys.stdout.write(')\\n')
return rootObj
USAGE_TEXT = \"\"\"
Usage: python ???.py <infilename>
\"\"\"
def usage():
print(USAGE_TEXT)
sys.exit(-1)
def main():
args = sys.argv[1:]
if len(args) != 1:
usage()
infilename = args[0]
root = parse(infilename)
if __name__ == '__main__':
main()
#import pdb
#pdb.run('main()')
"""
##def isMember(item, lst):
## for item1 in lst:
## if item == item1:
## print '(isMember) found name: %s' % item
## return True
## print '(isMember) did not find name: %s' % item
## return False
def generateSubclasses(root, subclassFilename, behaviorFilename, prefix, superModule="xxx"):
name = root.getChildren()[0].getName()
subclassFile = makeFile(subclassFilename)
if subclassFile:
# Read in the XMLBehavior file.
xmlbehavior = None
behaviors = None
baseUrl = None
if behaviorFilename:
try:
# Add the correct working directory to the path so that
# we use the user/developers local copy.
sys.path.insert(0, ".")
import xmlbehavior_sub as xmlbehavior
except ImportError:
print("*** You have requested generation of extended methods.")
print("*** But, no xmlbehavior module is available.")
print("*** Generation of extended behavior methods is omitted.")
if xmlbehavior:
behaviors = xmlbehavior.parse(behaviorFilename)
behaviors.make_class_dictionary(cleanupName)
baseUrl = behaviors.getBase_impl_url()
wrt = subclassFile.write
wrt(TEMPLATE_SUBCLASS_HEADER % (time.ctime(), superModule))
for element in ElementsForSubclasses:
generateSubclass(subclassFile, element, prefix, xmlbehavior, behaviors, baseUrl)
## processed = []
## for element in root.getChildren():
## name = element.getCleanName()
## if name not in processed:
## processed.append(name)
## generateSubclass(subclassFile, element, prefix, xmlbehavior, behaviors, baseUrl)
## while 1:
## if len(DelayedElements_subclass) <= 0:
## break
## element = DelayedElements_subclass.pop()
## name = element.getCleanName()
## if name not in processed:
## processed.append(name)
## generateSubclass(subclassFile, element, prefix, xmlbehavior, behaviors, baseUrl)
name = root.getChildren()[0].getName()
elType = cleanupName(root.getChildren()[0].getType())
if RootElement:
rootElement = RootElement
else:
rootElement = elType
params = {
"cap_name": cleanupName(name).capitalize(),
"name": cleanupName(name),
"module_name": os.path.splitext(os.path.basename(subclassFilename))[0],
"root": rootElement,
"super": superModule,
}
wrt(TEMPLATE_SUBCLASS_FOOTER % params)
subclassFile.close()
def generateFromTree(outfile, prefix, elements, processed):
for element in elements:
name = element.getCleanName()
if 1: # if name not in processed:
processed.append(name)
generateClasses(outfile, prefix, element, 0)
children = element.getChildren()
if children:
generateFromTree(outfile, prefix, element.getChildren(), processed)
def generate(outfileName, subclassFilename, behaviorFilename, prefix, root, superModule):
global DelayedElements, DelayedElements_subclass
# Create an output file.
# Note that even if the user does not request an output file,
# we still need to go through the process of generating classes
# because it produces data structures needed during generation of
# subclasses.
outfile = None
if outfileName:
outfile = makeFile(outfileName)
if not outfile:
outfile = os.tmpfile()
processed = []
generateHeader(outfile, prefix)
DelayedElements = []
DelayedElements_subclass = []
elements = root.getChildren()
generateFromTree(outfile, prefix, elements, processed)
while 1:
if len(DelayedElements) <= 0:
break
element = DelayedElements.pop()
name = element.getCleanName()
if name not in processed:
processed.append(name)
generateClasses(outfile, prefix, element, 1)
#
# Generate the elements that were postponed because we had not
# yet generated their base class.
idx = 0
while 1:
if len(PostponedExtensions) <= 0:
break
element = PostponedExtensions.pop()
base = element.getBase()
if base and base in ElementDict:
parent = ElementDict[base]
parentName = parent.getName()
if parentName not in AlreadyGenerated:
PostponedExtensions.insert(0, element)
else:
idx += 1
generateClasses(outfile, prefix, element, 1)
#
# Disable the generation of SAX handler/parser.
# It failed when we stopped putting simple types into ElementDict.
# When there are duplicate names, the SAX parser probably does
# not work anyway.
generateSAXHndlr(outfile, root)
generateMain(outfile, prefix, root)
outfile.close()
if subclassFilename:
generateSubclasses(root, subclassFilename, behaviorFilename, prefix, superModule)
def makeFile(outFileName):
global Force
outFile = None
if (not Force) and os.path.exists(outFileName):
reply = input("File %s exists. Overwrite? (y/n): " % outFileName)
if reply == "y":
outFile = open(outFileName, "w")
else:
outFile = open(outFileName, "w")
return outFile
def mapName(oldName):
global NameTable
newName = oldName
if NameTable:
if oldName in NameTable:
newName = NameTable[oldName]
return newName
def cleanupName(oldName):
newName = oldName.replace(":", "_")
newName = newName.replace("-", "_")
return newName
## def mapName(oldName):
## return '_X_%s' % oldName
def strip_namespace(val):
return val.split(":")[-1]
def parseAndGenerate(
outfileName,
subclassFilename,
prefix,
xschemaFileName,
behaviorFilename,
superModule="???",
):
global DelayedElements, DelayedElements_subclass, AlreadyGenerated, SaxDelayedElements, AlreadyGenerated_subclass
DelayedElements = []
DelayedElements_subclass = []
AlreadyGenerated = []
AlreadyGenerated_subclass = []
## parser = saxexts.make_parser("xml.sax.drivers2.drv_pyexpat")
parser = make_parser()
## print 'dir(parser):', dir(parser)
## print "Parser: %s" % parser
dh = XschemaHandler()
## parser.setDocumentHandler(dh)
parser.setContentHandler(dh)
parser.parse(xschemaFileName)
root = dh.getRoot()
root.annotate()
## print 'ElementDict:', ElementDict
## for name, obj in ElementDict.items():
## print ' ', name, obj.getName(), obj.type
## print '=' * 50
## root.show(sys.stdout, 0)
## print '=' * 50
## response = input('Press Enter')
## root.show(sys.stdout, 0)
## print '=' * 50
## print ']]] root: ', root, '[[['
generate(outfileName, subclassFilename, behaviorFilename, prefix, root, superModule)
USAGE_TEXT = """
Usage: python generateDS.py [ options ] <in_xsd_file>
Options:
-o <outfilename> Output file name for data representation classes
-s <subclassfilename> Output file name for subclasses
-p <prefix> Prefix string to be prepended to the class names
-n <mappingfilename> Transform names with table in mappingfilename.
-f Force creation of output files. Do not ask.
-a <namespaceabbrev> Namespace abbreviation, e.g. "xsd:". Default = 'xs:'.
-b <behaviorfilename> Input file name for behaviors added to subclasses
-m Generate properties for member variables
--subclass-suffix="XXX" Append XXX to the generated subclass names. Default="Sub".
--root-element="XXX" Assume XXX is root element of instance docs.
Default is first element defined in schema.
--super="XXX" Super module name in subclass module. Default="???"
Example:
python generateDS.py -o generateModel_Module.py generateMetaModel_Module.xsd
"""
def usage():
print(USAGE_TEXT)
sys.exit(-1)
def main():
global Force, GenerateProperties, SubclassSuffix, RootElement
args = sys.argv[1:]
options, args = getopt.getopt(
args,
"fyo:s:p:a:b:m",
[
"subclass-suffix=",
"root-element=",
"super=",
],
)
prefix = ""
outFilename = None
subclassFilename = None
behaviorFilename = None
nameSpace = "xs:"
debug = 0
superModule = "???"
for option in options:
if option[0] == "-p":
prefix = option[1]
elif option[0] == "-o":
outFilename = option[1]
elif option[0] == "-s":
subclassFilename = option[1]
elif option[0] == "-f":
Force = 1
elif option[0] == "-a":
nameSpace = option[1]
elif option[0] == "-b":
behaviorFilename = option[1]
elif option[0] == "-m":
GenerateProperties = 1
elif option[0] == "--subclass-suffix":
SubclassSuffix = option[1]
elif option[0] == "--root-element":
RootElement = option[1]
elif option[0] == "--super":
superModule = option[1]
set_type_constants(nameSpace)
if behaviorFilename and not subclassFilename:
print("\n*** Error. -b requires -s")
usage()
if len(args) != 1:
usage()
xschemaFileName = args[0]
if debug:
pass
else:
parseAndGenerate(
outFilename,
subclassFilename,
prefix,
xschemaFileName,
behaviorFilename,
superModule=superModule,
)
if __name__ == "__main__":
main()
## import pdb
## pdb.run('main()')
|