#!/usr/bin/env python
# -*- coding: utf-8 -*- 

#
# Generated Wed Nov 14 14:02:56 2012 by generateDS.py version 2.7c.
#

import sys
import getopt
import re as re_

import stix.bindings.stix_common_0_2 as stix_common_binding


abs_impl = {'TLPHandlingGuidanceType' : {   'module':'stix_common_0_2',
                                            'python_name':'TLPHandlingGuidanceType',
                                            'namespace_prefix':'stixCommon',
                                            'namespace':'http://stix.mitre.org/Common',
                                            'schema_location':'STIX-Common_v02.xsd',
                                        }
            }




etree_ = None
Verbose_import_ = False
(   XMLParser_import_none, XMLParser_import_lxml,
    XMLParser_import_elementtree
    ) = range(3)
XMLParser_import_library = None
try:
    # lxml
    from lxml import etree as etree_
    XMLParser_import_library = XMLParser_import_lxml
    if Verbose_import_:
        print("running with lxml.etree")
except ImportError:
    try:
        # cElementTree from Python 2.5+
        import xml.etree.cElementTree as etree_
        XMLParser_import_library = XMLParser_import_elementtree
        if Verbose_import_:
            print("running with cElementTree on Python 2.5+")
    except ImportError:
        try:
            # ElementTree from Python 2.5+
            import xml.etree.ElementTree as etree_
            XMLParser_import_library = XMLParser_import_elementtree
            if Verbose_import_:
                print("running with ElementTree on Python 2.5+")
        except ImportError:
            try:
                # normal cElementTree install
                import cElementTree as etree_
                XMLParser_import_library = XMLParser_import_elementtree
                if Verbose_import_:
                    print("running with cElementTree")
            except ImportError:
                try:
                    # normal ElementTree install
                    import elementtree.ElementTree as etree_
                    XMLParser_import_library = XMLParser_import_elementtree
                    if Verbose_import_:
                        print("running with ElementTree")
                except ImportError:
                    raise ImportError("Failed to import ElementTree from any known place")

def parsexml_(*args, **kwargs):
    if (XMLParser_import_library == XMLParser_import_lxml and
        'parser' not in kwargs):
        # Use the lxml ElementTree compatible parser so that, e.g.,
        #   we ignore comments.
        kwargs['parser'] = etree_.ETCompatXMLParser()
    doc = etree_.parse(*args, **kwargs)
    return doc

#
# User methods
#
# Calls to the methods in these classes are generated by generateDS.py.
# You can replace these methods by re-implementing the following class
#   in a module named generatedssuper.py.

try:
    from generatedssuper import GeneratedsSuper
except ImportError, exp:

    class GeneratedsSuper(object):
        def gds_format_string(self, input_data, input_name=''):
            return input_data
        def gds_validate_string(self, input_data, node, input_name=''):
            return input_data
        def gds_format_integer(self, input_data, input_name=''):
            return '%d' % input_data
        def gds_validate_integer(self, input_data, node, input_name=''):
            return input_data
        def gds_format_integer_list(self, input_data, input_name=''):
            return '%s' % input_data
        def gds_validate_integer_list(self, input_data, node, input_name=''):
            values = input_data.split()
            for value in values:
                try:
                    fvalue = float(value)
                except (TypeError, ValueError), exp:
                    raise_parse_error(node, 'Requires sequence of integers')
            return input_data
        def gds_format_float(self, input_data, input_name=''):
            return '%f' % input_data
        def gds_validate_float(self, input_data, node, input_name=''):
            return input_data
        def gds_format_float_list(self, input_data, input_name=''):
            return '%s' % input_data
        def gds_validate_float_list(self, input_data, node, input_name=''):
            values = input_data.split()
            for value in values:
                try:
                    fvalue = float(value)
                except (TypeError, ValueError), exp:
                    raise_parse_error(node, 'Requires sequence of floats')
            return input_data
        def gds_format_double(self, input_data, input_name=''):
            return '%e' % input_data
        def gds_validate_double(self, input_data, node, input_name=''):
            return input_data
        def gds_format_double_list(self, input_data, input_name=''):
            return '%s' % input_data
        def gds_validate_double_list(self, input_data, node, input_name=''):
            values = input_data.split()
            for value in values:
                try:
                    fvalue = float(value)
                except (TypeError, ValueError), exp:
                    raise_parse_error(node, 'Requires sequence of doubles')
            return input_data
        def gds_format_boolean(self, input_data, input_name=''):
            return '%s' % input_data
        def gds_validate_boolean(self, input_data, node, input_name=''):
            return input_data
        def gds_format_boolean_list(self, input_data, input_name=''):
            return '%s' % input_data
        def gds_validate_boolean_list(self, input_data, node, input_name=''):
            values = input_data.split()
            for value in values:
                if value not in ('true', '1', 'false', '0', ):
                    raise_parse_error(node, 'Requires sequence of booleans ("true", "1", "false", "0")')
            return input_data
        def gds_str_lower(self, instring):
            return instring.lower()
        def get_path_(self, node):
            path_list = []
            self.get_path_list_(node, path_list)
            path_list.reverse()
            path = '/'.join(path_list)
            return path
        Tag_strip_pattern_ = re_.compile(r'\{.*\}')
        def get_path_list_(self, node, path_list):
            if node is None:
                return
            tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag)
            if tag:
                path_list.append(tag)
            self.get_path_list_(node.getparent(), path_list)
        def get_class_obj_(self, node, default_class=None):
            class_obj1 = default_class
            if 'xsi' in node.nsmap:
                classname = node.get('{%s}type' % node.nsmap['xsi'])
                if classname is not None:
                    names = classname.split(':')
                    if len(names) == 2:
                        classname = names[1]
                    class_obj2 = globals().get(classname)
                    if class_obj2 is not None:
                        class_obj1 = class_obj2
            return class_obj1
        def gds_build_any(self, node, type_name=None):
            return None


#
# 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')

#
# Globals
#

ExternalEncoding = 'ascii'
Tag_pattern_ = re_.compile(r'({.*})?(.*)')
String_cleanup_pat_ = re_.compile(r"[\n\r\s]+")
Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)')

#
# Support/utility functions.
#

def showIndent(outfile, level, pretty_print=True):
    if pretty_print:
        for idx in range(level):
            outfile.write('    ')

def quote_xml(inStr):
    if not inStr:
        return ''
    s1 = (isinstance(inStr, basestring) and inStr or
          '%s' % inStr)
    s1 = s1.replace('&', '&amp;')
    s1 = s1.replace('<', '&lt;')
    s1 = s1.replace('>', '&gt;')
    return s1

def quote_attrib(inStr):
    s1 = (isinstance(inStr, basestring) and inStr or
          '%s' % inStr)
    s1 = s1.replace('&', '&amp;')
    s1 = s1.replace('<', '&lt;')
    s1 = s1.replace('>', '&gt;')
    if '"' in s1:
        if "'" in s1:
            s1 = '"%s"' % s1.replace('"', "&quot;")
        else:
            s1 = "'%s'" % s1
    else:
        s1 = '"%s"' % s1
    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

def get_all_text_(node):
    if node.text is not None:
        text = node.text
    else:
        text = ''
    for child in node:
        if child.tail is not None:
            text += child.tail
    return text

def find_attr_value_(attr_name, node):
    attrs = node.attrib
    attr_parts = attr_name.split(':')
    value = None
    if len(attr_parts) == 1:
        value = attrs.get(attr_name)
    elif len(attr_parts) == 2:
        prefix, name = attr_parts
        namespace = node.nsmap.get(prefix)
        if namespace is not None:
            value = attrs.get('{%s}%s' % (namespace, name, ))
    return value


class GDSParseError(Exception):
    pass

def raise_parse_error(node, msg):
    if XMLParser_import_library == XMLParser_import_lxml:
        msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, )
    else:
        msg = '%s (element %s)' % (msg, node.tag, )
    raise GDSParseError(msg)


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, namespace, pretty_print=True):
        if self.category == MixedContainer.CategoryText:
            # Prevent exporting empty content as empty lines.
            if self.value.strip(): 
                outfile.write(self.value)
        elif self.category == MixedContainer.CategorySimple:
            self.exportSimple(outfile, level, name)
        else:    # category == MixedContainer.CategoryComplex
            self.value.export(outfile, level, namespace, name, pretty_print)
    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('model_.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('model_.MixedContainer(%d, %d, "%s", "%s"),\n' % \
                (self.category, self.content_type, self.name, self.value))
        else:    # category == MixedContainer.CategoryComplex
            showIndent(outfile, level)
            outfile.write('model_.MixedContainer(%d, %d, "%s",\n' % \
                (self.category, self.content_type, self.name,))
            self.value.exportLiteral(outfile, level + 1)
            showIndent(outfile, level)
            outfile.write(')\n')


class MemberSpec_(object):
    def __init__(self, name='', data_type='', container=0):
        self.name = name
        self.data_type = data_type
        self.container = container
    def set_name(self, name): self.name = name
    def get_name(self): return self.name
    def set_data_type(self, data_type): self.data_type = data_type
    def get_data_type_chain(self): return self.data_type
    def get_data_type(self):
        if isinstance(self.data_type, list):
            if len(self.data_type) > 0:
                return self.data_type[-1]
            else:
                return 'xs:string'
        else:
            return self.data_type
    def set_container(self, container): self.container = container
    def get_container(self): return self.container

def _cast(typ, value):
    if typ is None or value is None:
        return value
    return typ(value)

#
# Data representation classes.
#

class MarkingType1(GeneratedsSuper):
    """Specifies a unique ID for this Marking.Specifies a reference to the
    ID of a Marking defined elsewhere.Specifies the relevant
    Data_Marking schema version for this content."""
    subclass = None
    superclass = None
    def __init__(self, idref=None, id=None, version=None, ControlledStructure=None, Marking_Structure=None, InformationSource=None):
        self.idref = _cast(None, idref)
        self.id = _cast(None, id)
        self.version = _cast(None, version)
        self.ControlledStructure = ControlledStructure
        if Marking_Structure is None:
            self.Marking_Structure = []
        else:
            self.Marking_Structure = Marking_Structure
        self.InformationSource = InformationSource
    def factory(*args_, **kwargs_):
        if MarkingType1.subclass:
            return MarkingType1.subclass(*args_, **kwargs_)
        else:
            return MarkingType1(*args_, **kwargs_)
    factory = staticmethod(factory)
    def get_ControlledStructure(self): return self.ControlledStructure
    def set_ControlledStructure(self, ControlledStructure): self.ControlledStructure = ControlledStructure
    def get_Marking_Structure(self): return self.Marking_Structure
    def set_Marking_Structure(self, Marking_Structure): self.Marking_Structure = Marking_Structure
    def add_Marking_Structure(self, value): self.Marking_Structure.append(value)
    def insert_Marking_Structure(self, index, value): self.Marking_Structure[index] = value
    def get_InformationSource(self): return self.InformationSource
    def set_InformationSource(self, InformationSource): self.InformationSource = InformationSource
    def get_idref(self): return self.idref
    def set_idref(self, idref): self.idref = idref
    def get_id(self): return self.id
    def set_id(self, id): self.id = id
    def get_version(self): return self.version
    def set_version(self, version): self.version = version
    def export(self, outfile, level, namespace_='marking:', name_='MarkingType', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        showIndent(outfile, level, pretty_print)
        outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = []
        self.exportAttributes(outfile, level, already_processed, namespace_, name_='MarkingType')
        if self.hasContent_():
            outfile.write('>%s' % (eol_, ))
            self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
            showIndent(outfile, level, pretty_print)
            outfile.write('</%s%s>%s' % (namespace_, name_, eol_))
        else:
            outfile.write('/>%s' % (eol_, ))
    def exportAttributes(self, outfile, level, already_processed, namespace_='marking:', name_='MarkingType'):
        if self.idref is not None and 'idref' not in already_processed:
            already_processed.append('idref')
            outfile.write(' idref=%s' % (quote_attrib(self.idref), ))
        if self.id is not None and 'id' not in already_processed:
            already_processed.append('id')
            outfile.write(' id=%s' % (quote_attrib(self.id), ))
        if self.version is not None and 'version' not in already_processed:
            already_processed.append('version')
            outfile.write(' version=%s' % (self.gds_format_string(quote_attrib(self.version).encode(ExternalEncoding), input_name='version'), ))
    def exportChildren(self, outfile, level, namespace_='marking:', name_='MarkingType', fromsubclass_=False, pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        if self.ControlledStructure is not None:
            showIndent(outfile, level, pretty_print)
            outfile.write('<%sControlledStructure>%s</%sControlledStructure>%s' % (namespace_, self.gds_format_string(quote_xml(self.ControlledStructure).encode(ExternalEncoding), input_name='ControlledStructure'), namespace_, eol_))
        for Marking_Structure_ in self.get_Marking_Structure():
            Marking_Structure_.export(outfile, level, namespace_, name_='Marking_Structure', pretty_print=pretty_print)
        if self.InformationSource is not None:
            self.InformationSource.export(outfile, level, namespace_, name_='InformationSource', pretty_print=pretty_print)
    def hasContent_(self):
        if (
            self.ControlledStructure is not None or
            self.Marking_Structure or
            self.InformationSource is not None
            ):
            return True
        else:
            return False
    def exportLiteral(self, outfile, level, name_='MarkingType'):
        level += 1
        self.exportLiteralAttributes(outfile, level, [], name_)
        if self.hasContent_():
            self.exportLiteralChildren(outfile, level, name_)
    def exportLiteralAttributes(self, outfile, level, already_processed, name_):
        if self.idref is not None and 'idref' not in already_processed:
            already_processed.append('idref')
            showIndent(outfile, level)
            outfile.write('idref = %s,\n' % (self.idref,))
        if self.id is not None and 'id' not in already_processed:
            already_processed.append('id')
            showIndent(outfile, level)
            outfile.write('id = %s,\n' % (self.id,))
        if self.version is not None and 'version' not in already_processed:
            already_processed.append('version')
            showIndent(outfile, level)
            outfile.write('version = "%s",\n' % (self.version,))
    def exportLiteralChildren(self, outfile, level, name_):
        if self.ControlledStructure is not None:
            showIndent(outfile, level)
            outfile.write('ControlledStructure=%s,\n' % quote_python(self.ControlledStructure).encode(ExternalEncoding))
        showIndent(outfile, level)
        outfile.write('Marking_Structure=[\n')
        level += 1
        for Marking_Structure_ in self.Marking_Structure:
            showIndent(outfile, level)
            outfile.write('model_.MarkingStructureType(\n')
            Marking_Structure_.exportLiteral(outfile, level, name_='MarkingStructureType')
            showIndent(outfile, level)
            outfile.write('),\n')
        level -= 1
        showIndent(outfile, level)
        outfile.write('],\n')
        if self.InformationSource is not None:
            showIndent(outfile, level)
            outfile.write('InformationSource=model_.InformationSourceType(\n')
            self.InformationSource.exportLiteral(outfile, level, name_='InformationSource')
            showIndent(outfile, level)
            outfile.write('),\n')
    def build(self, node):
        self.buildAttributes(node, node.attrib, [])
        for child in node:
            nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
            self.buildChildren(child, node, nodeName_)
    def buildAttributes(self, node, attrs, already_processed):
        value = find_attr_value_('idref', node)
        if value is not None and 'idref' not in already_processed:
            already_processed.append('idref')
            self.idref = value
        value = find_attr_value_('id', node)
        if value is not None and 'id' not in already_processed:
            already_processed.append('id')
            self.id = value
        value = find_attr_value_('version', node)
        if value is not None and 'version' not in already_processed:
            already_processed.append('version')
            self.version = value
    def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
        if nodeName_ == 'ControlledStructure':
            ControlledStructure_ = child_.text
            ControlledStructure_ = self.gds_validate_string(ControlledStructure_, node, 'ControlledStructure')
            self.ControlledStructure = ControlledStructure_
        elif nodeName_ == 'Marking_Structure':
            type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type')
            if type_name_ is None:
                raise NotImplementedError('No implementation given')
                #type_name_ = child_.attrib.get('type')
            if type_name_ is not None:
                type_names_ = type_name_.split(':')
                if len(type_names_) == 1:
                    type_name_ = type_names_[0]
                else:
                    type_name_ = type_names_[1] 
                    
                type_map = abs_impl.get(type_name_)
                class_ = getattr(__import__(type_map.get('module'), globals(), fromlist=[type_map.get('python_name')]),type_map.get('python_name'))
                obj_ = class_.factory()
                obj_.build(child_)
            else:
                raise NotImplementedError(
                    'Class not implemented for <Defined_Object> element')
            self.Marking_Structure.append(obj_)
            
        elif nodeName_ == 'InformationSource':
            obj_ = stix_common_binding.InformationSourceType.factory()
            obj_.build(child_)
            self.set_InformationSource(obj_)
# end class MarkingType1







class MarkingType(GeneratedsSuper):
    """MarkingType specifies a structure for marking information to be
    applied to portions of XML content."""
    subclass = None
    superclass = None
    def __init__(self, Marking=None):
        if Marking is None:
            self.Marking = []
        else:
            self.Marking = Marking
    def factory(*args_, **kwargs_):
        if MarkingType.subclass:
            return MarkingType.subclass(*args_, **kwargs_)
        else:
            return MarkingType(*args_, **kwargs_)
    factory = staticmethod(factory)
    def get_Marking(self): return self.Marking
    def set_Marking(self, Marking): self.Marking = Marking
    def add_Marking(self, value): self.Marking.append(value)
    def insert_Marking(self, index, value): self.Marking[index] = value
    def export(self, outfile, level, namespace_='marking:', name_='MarkingType', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        showIndent(outfile, level, pretty_print)
        outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = []
        self.exportAttributes(outfile, level, already_processed, namespace_, name_='MarkingType')
        if self.hasContent_():
            outfile.write('>%s' % (eol_, ))
            self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
            showIndent(outfile, level, pretty_print)
            outfile.write('</%s%s>%s' % (namespace_, name_, eol_))
        else:
            outfile.write('/>%s' % (eol_, ))
    def exportAttributes(self, outfile, level, already_processed, namespace_='marking:', name_='MarkingType'):
        pass
    def exportChildren(self, outfile, level, namespace_='marking:', name_='MarkingType', fromsubclass_=False, pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        for Marking_ in self.Marking:
            Marking_.export(outfile, level, 'marking:', name_='Marking', pretty_print=pretty_print)
    def hasContent_(self):
        if (
            self.Marking
            ):
            return True
        else:
            return False
    def exportLiteral(self, outfile, level, name_='MarkingType'):
        level += 1
        self.exportLiteralAttributes(outfile, level, [], name_)
        if self.hasContent_():
            self.exportLiteralChildren(outfile, level, name_)
    def exportLiteralAttributes(self, outfile, level, already_processed, name_):
        pass
    def exportLiteralChildren(self, outfile, level, name_):
        showIndent(outfile, level)
        outfile.write('Marking=[\n')
        level += 1
        for Marking_ in self.Marking:
            showIndent(outfile, level)
            outfile.write('model_.MarkingType1(\n')
            Marking_.exportLiteral(outfile, level, name_='MarkingType1')
            showIndent(outfile, level)
            outfile.write('),\n')
        level -= 1
        showIndent(outfile, level)
        outfile.write('],\n')
    def build(self, node):
        self.buildAttributes(node, node.attrib, [])
        for child in node:
            nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
            self.buildChildren(child, node, nodeName_)
    def buildAttributes(self, node, attrs, already_processed):
        pass
    def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
        if nodeName_ == 'Marking':
            obj_ = MarkingType1.factory()
            obj_.build(child_)
            self.Marking.append(obj_)
# end class MarkingType


class MarkingStructureType(GeneratedsSuper):
    """The MarkingStructureType contains the marking information to be
    applied to a portion of XML content. This type is defined as an
    abstract type that enables the flexibility to utilize any
    variety of marking structures.This field specifies the name of
    the marking model to be applied within this
    Marking_Structure.This field contains a reference to an
    authoritative source on the marking model to be applied within
    this Marking_Structure."""
    subclass = None
    superclass = None
    def __init__(self, markingModelRef=None, markingModelName=None, extensiontype_=None):
        self.markingModelRef = _cast(None, markingModelRef)
        self.markingModelName = _cast(None, markingModelName)
        self.extension_type_ = None
        pass
    def factory(*args_, **kwargs_):
        if MarkingStructureType.subclass:
            return MarkingStructureType.subclass(*args_, **kwargs_)
        else:
            return MarkingStructureType(*args_, **kwargs_)
    factory = staticmethod(factory)
    def get_extensiontype_(self): return self.extensiontype_
    def set_extensiontype_(self): return self.extensiontype_
    def get_markingModelRef(self): return self.markingModelRef
    def set_markingModelRef(self, markingModelRef): self.markingModelRef = markingModelRef
    def get_markingModelName(self): return self.markingModelName
    def set_markingModelName(self, markingModelName): self.markingModelName = markingModelName
    def export(self, outfile, level, namespace_='marking:', name_='MarkingStructureType', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        showIndent(outfile, level, pretty_print)
        outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = []
        self.exportAttributes(outfile, level, already_processed, namespace_, name_='MarkingStructureType')
        if self.hasContent_():
            outfile.write('>%s' % (eol_, ))
            self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
            outfile.write('</%s%s>%s' % (namespace_, name_, eol_))
        else:
            outfile.write('/>%s' % (eol_, ))
    def exportAttributes(self, outfile, level, already_processed, namespace_='marking:', name_='MarkingStructureType'):
        if self.markingModelRef is not None and 'markingModelRef' not in already_processed:
            already_processed.append('markingModelRef')
            outfile.write(' markingModelRef=%s' % (self.gds_format_string(quote_attrib(self.markingModelRef).encode(ExternalEncoding), input_name='markingModelRef'), ))
        if self.markingModelName is not None and 'markingModelName' not in already_processed:
            already_processed.append('markingModelName')
            outfile.write(' markingModelName=%s' % (quote_attrib(self.markingModelName), ))
        if self.extensiontype_ is not None and 'xsi:type' not in already_processed:
            already_processed.append('xsi:type')
            outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"')
            outfile.write(' xsi:type="%s"' % self.extensiontype_)

    def exportChildren(self, outfile, level, namespace_='marking:', name_='MarkingStructureType', fromsubclass_=False, pretty_print=True):
        pass
    def hasContent_(self):
        if (

            ):
            return True
        else:
            return False
    def exportLiteral(self, outfile, level, name_='MarkingStructureType'):
        level += 1
        self.exportLiteralAttributes(outfile, level, [], name_)
        if self.hasContent_():
            self.exportLiteralChildren(outfile, level, name_)
    def exportLiteralAttributes(self, outfile, level, already_processed, name_):
        if self.markingModelRef is not None and 'markingModelRef' not in already_processed:
            already_processed.append('markingModelRef')
            showIndent(outfile, level)
            outfile.write('markingModelRef = "%s",\n' % (self.markingModelRef,))
        if self.markingModelName is not None and 'markingModelName' not in already_processed:
            already_processed.append('markingModelName')
            showIndent(outfile, level)
            outfile.write('markingModelName = %s,\n' % (self.markingModelName,))
    def exportLiteralChildren(self, outfile, level, name_):
        pass
    def build(self, node):
        self.buildAttributes(node, node.attrib, [])
        for child in node:
            nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
            self.buildChildren(child, node, nodeName_)
    def buildAttributes(self, node, attrs, already_processed):
        value = find_attr_value_('markingModelRef', node)
        if value is not None and 'markingModelRef' not in already_processed:
            already_processed.append('markingModelRef')
            self.markingModelRef = value
        value = find_attr_value_('markingModelName', node)
        if value is not None and 'markingModelName' not in already_processed:
            already_processed.append('markingModelName')
            self.markingModelName = value
            
        value = find_attr_value_('xsi:type', node)
        if value is not None and 'xsi:type' not in already_processed:
            already_processed.append('xsi:type')
            self.extensiontype_ = value  
    def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
        pass
# end class MarkingStructureType





#===============================================================================
# class TLPHandlingGuidanceType(MarkingStructureType):
#   """The TLPHandlingGuidanceType is an extension of the abstract
#   data_marking_binding.MarkingStructureType that enables the specification of Traffic
#   Light Protocol guidance markings.
#   
#   This is copied from stix_common_0_2 because the globals() lookup fails when
#   resolving the implementation of abstract data types
#   """
#   subclass = None
#   superclass = MarkingStructureType
#   def __init__(self, markingModelRef=None, markingModelName=None, sensitivity=None):
#       super(TLPHandlingGuidanceType, self).__init__(markingModelRef, markingModelName, )
#       self.sensitivity = _cast(None, sensitivity)
#       pass
#   def factory(*args_, **kwargs_):
#       if TLPHandlingGuidanceType.subclass:
#           return TLPHandlingGuidanceType.subclass(*args_, **kwargs_)
#       else:
#           return TLPHandlingGuidanceType(*args_, **kwargs_)
#   factory = staticmethod(factory)
#   def get_sensitivity(self): return self.sensitivity
#   def set_sensitivity(self, sensitivity): self.sensitivity = sensitivity
#   def export(self, outfile, level, namespace_='stixCommon:', name_='TLPHandlingGuidanceType', namespacedef_='', pretty_print=True):
#       if pretty_print:
#           eol_ = '\n'
#       else:
#           eol_ = ''
#       showIndent(outfile, level, pretty_print)
#       outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
#       already_processed = []
#       self.exportAttributes(outfile, level, already_processed, namespace_, name_='TLPHandlingGuidanceType')
#       if self.hasContent_():
#           outfile.write('>%s' % (eol_, ))
#           self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
#           outfile.write('</%s%s>%s' % (namespace_, name_, eol_))
#       else:
#           outfile.write('/>%s' % (eol_, ))
#   def exportAttributes(self, outfile, level, already_processed, namespace_='stixCommon:', name_='TLPHandlingGuidanceType'):
#       super(TLPHandlingGuidanceType, self).exportAttributes(outfile, level, already_processed, namespace_, name_='TLPHandlingGuidanceType')
#       if self.sensitivity is not None and 'sensitivity' not in already_processed:
#           already_processed.append('sensitivity')
#           outfile.write(' sensitivity=%s' % (quote_attrib(self.sensitivity), ))
#   def exportChildren(self, outfile, level, namespace_='stixCommon:', name_='TLPHandlingGuidanceType', fromsubclass_=False, pretty_print=True):
#       super(TLPHandlingGuidanceType, self).exportChildren(outfile, level, 'stixCommon:', name_, True, pretty_print=pretty_print)
#       pass
#   def hasContent_(self):
#       if (
#           super(TLPHandlingGuidanceType, self).hasContent_()
#           ):
#           return True
#       else:
#           return False
#   def exportLiteral(self, outfile, level, name_='TLPHandlingGuidanceType'):
#       level += 1
#       self.exportLiteralAttributes(outfile, level, [], name_)
#       if self.hasContent_():
#           self.exportLiteralChildren(outfile, level, name_)
#   def exportLiteralAttributes(self, outfile, level, already_processed, name_):
#       if self.sensitivity is not None and 'sensitivity' not in already_processed:
#           already_processed.append('sensitivity')
#           showIndent(outfile, level)
#           outfile.write('sensitivity = %s,\n' % (self.sensitivity,))
#       super(TLPHandlingGuidanceType, self).exportLiteralAttributes(outfile, level, already_processed, name_)
#   def exportLiteralChildren(self, outfile, level, name_):
#       super(TLPHandlingGuidanceType, self).exportLiteralChildren(outfile, level, name_)
#       pass
#   def build(self, node):
#       self.buildAttributes(node, node.attrib, [])
#       for child in node:
#           nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
#           self.buildChildren(child, node, nodeName_)
#   def buildAttributes(self, node, attrs, already_processed):
#       value = find_attr_value_('sensitivity', node)
#       if value is not None and 'sensitivity' not in already_processed:
#           already_processed.append('sensitivity')
#           self.sensitivity = value
#       super(TLPHandlingGuidanceType, self).buildAttributes(node, attrs, already_processed)
#   def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
#       super(TLPHandlingGuidanceType, self).buildChildren(child_, node, nodeName_, True)
#       pass
# # end class TLPHandlingGuidanceType
#===============================================================================




USAGE_TEXT = """
Usage: python <Parser>.py [ -s ] <in_xml_file>
"""

def usage():
    print(USAGE_TEXT)
    sys.exit(1)

def get_root_tag(node):
    tag = Tag_pattern_.match(node.tag).groups()[-1]
    rootClass = globals().get(tag)
    return tag, rootClass

def parse(inFileName):
    doc = parsexml_(inFileName)
    rootNode = doc.getroot()
    rootTag, rootClass = get_root_tag(rootNode)
    if rootClass is None:
        rootTag = 'MarkingType'
        rootClass = MarkingType
    rootObj = rootClass.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_=rootTag,
        namespacedef_='',
        pretty_print=True)
    return rootObj

def parseString(inString):
    from StringIO import StringIO
    doc = parsexml_(StringIO(inString))
    rootNode = doc.getroot()
    rootTag, rootClass = get_root_tag(rootNode)
    if rootClass is None:
        rootTag = 'MarkingType'
        rootClass = MarkingType
    rootObj = rootClass.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_="MarkingType",
        namespacedef_='')
    return rootObj

def parseLiteral(inFileName):
    doc = parsexml_(inFileName)
    rootNode = doc.getroot()
    rootTag, rootClass = get_root_tag(rootNode)
    if rootClass is None:
        rootTag = 'MarkingType'
        rootClass = MarkingType
    rootObj = rootClass.factory()
    rootObj.build(rootNode)
    # Enable Python to collect the space used by the DOM.
    doc = None
    sys.stdout.write('#from data_marking_0_5 import *\n\n')
    sys.stdout.write('import stix.bindings.data_marking_0_5 as data_marking_binding as model_\n\n')
    sys.stdout.write('rootObj = model_.rootTag(\n')
    rootObj.exportLiteral(sys.stdout, 0, name_=rootTag)
    sys.stdout.write(')\n')
    return rootObj

def main():
    args = sys.argv[1:]
    if len(args) == 1:
        parse(args[0])
    else:
        usage()

if __name__ == '__main__':
    #import pdb; pdb.set_trace()
    main()

__all__ = [
    "MarkingType",
    "MarkingStructureType"
    ]
