Next / Previous / Contents / TCC Help System / NM Tech homepage

4.5. processInput(): Read the schema

This function reads the schema, extracts the element and attribute names, and returns the nameTable dictionary with the Python/XML name pairs.

pyrang
def processInput(args):
    """Process the input schema.

      [ args is an Args object ->
          if args.inFileName names a readable file containing a
          valid RNG schema ->
            nameTable  :=  a dictionary whose keys are the Python
                manifest constant names for the element and
                attribute names in that schema (using args.prefix
                as a prefix), and each corresponding value is the
                XML name
          else ->
            sys.stderr  +:=  error message(s)
            stop execution ]
    """

First we create the name table as an empty dictionary.

pyrang
    #-- 1
    # [ nameTable  :=  a new, empty dictionary ]
    nameTable = {}

Next we attempt to open the input file and hand it to the et.parse() function to build an et.ElementTree.

pyrang
    #-- 2
    # [ if args.inFileName names a readable, well-formed XML file ->
    #     doc  :=  that file as an et.ElementTree
    #   else ->
    #     sys.stderr  +:=  error message
    #     stop execution ]
    try:
        doc = et.parse(args.inFileName)
    except (IOError, OSError) as x:
        fatal("Can't open '{0}' for reading: {1}".format(
              args.inFileName, str(x)))
    except et.XMLSyntaxError as x:
        fatal("File '{0}' is not well-formed: {1}".format(
              args.inFileName, str(x)))

Walking the tree to find all the element and attribute elements is quite easy with recursion. The function in Section 4.6, “findNames(): Recursive tree walker” is recursive, and finds all the names in a subtree rooted in the node you pass it as its first argument. In a DOM tree, the doc.documentElement attribute is the root Element node of the schema.

pyrang
    #-- 3
    # [ (nameTable is a dictionary) and
    #   (args is an Args object) ->
    #     nameTable  :=  nameTable with Python/XML name pairs added
    #         from the subtree rooted at doc.documentElement,
    #         with the names prefixed by args.prefix ]
    findNames(doc.getroot(), args, nameTable)

Finally, we return the nameTable dictionary we've built.

pyrang
    #-- 5
    return nameTable