Example #1
0
    def test_separate_namespace(self):
        """Tests the function that separates namespaces from qualified names"""

        namespace, element_name = separate_namespace('{garden}eggplant')
        self.assertEqual(namespace, 'garden')
        self.assertEqual(element_name, 'eggplant')

        namespace, element_name = separate_namespace('eggplant')
        self.assertEqual(namespace, None)
        self.assertEqual(element_name, 'eggplant')
Example #2
0
    def test_separate_namespace(self):
        """Tests the function that separates namespaces from qualified names"""
        from pykml.helpers import separate_namespace

        namespace, element_name = separate_namespace('{garden}eggplant')
        self.assertEqual(namespace, 'garden')
        self.assertEqual(element_name, 'eggplant')

        namespace, element_name = separate_namespace('eggplant')
        self.assertEqual(namespace, None)
        self.assertEqual(element_name, 'eggplant')
Example #3
0
def convert_placemark(placemark, wp_count=0, outFile=None):
    name = None
    prototype = None
    location = None
    points = []
    for elem in placemark.iterchildren():
        tag = helpers.separate_namespace(elem.tag)[1]

        if tag == 'name':
            name, prototype, script = parse_name(elem.text)
        elif tag == 'Point':
            location = str.split(elem.coordinates.text, ',')
            points.append('[]')
        elif tag == 'LineString':
            location = ['0', '0', '0']
            points.append('')
            for coordinate in re.split('\s+', elem.coordinates.text)[1:-1]:
                wp_name = 'wp'+str(wp_count)
                wp_loc = str.split(coordinate, ',')
                create_entity_element(wp_name, 'waypoint', wp_loc, outFile=outFile)
                wp_count += 1
                points.append(wp_name)

    create_entity_element(name, prototype, location, points=points, initScript=script, outFile=outFile)

    return wp_count
Example #4
0
def get_segment_data(placemark, wp_count=0, outFile=None):
    name = None
    points = []
    for elem in placemark.iterchildren():
        tag = helpers.separate_namespace(elem.tag)[1]
        if tag == 'name':
            name = re.sub('\s', '', elem.text)
        elif tag == 'LineString':
            for coordinate in re.split('\s+', elem.coordinates.text)[1:-1]:
                wp_loc = str.split(coordinate, ',')
                points.append(wp_loc[0:2])
    return name, points
Example #5
0
def write_python_script_for_kml_document(doc):
    "Generates a python script that will construct a given KML document"
    import StringIO
    from pykml.helpers import separate_namespace
    
    output = StringIO.StringIO()
    indent_size = 2
    
    # add the etree package so that comments can be handled
    output.write('from lxml import etree\n')
    
    # add the namespace declaration section
    output.write('from pykml.factory import KML_ElementMaker as KML\n')
    output.write('from pykml.factory import ATOM_ElementMaker as ATOM\n')
    output.write('from pykml.factory import GX_ElementMaker as GX\n')
    output.write('\n')
    
    level = 0
    xml = StringIO.StringIO(etree.tostring(doc))
    context = etree.iterparse(xml, events=("start", "end", "comment"))
    output.write('doc = ')
    last_action = None
    main_element_processed_flag = False
    previous_list = []  # list of comments before the root element
    posterior_list = []  # list of comments after the root element
    for action, elem in context:
        # TODO: remove the following redundant conditional
        if action in ('start','end','comment'):
            namespace, element_name = separate_namespace(elem.tag)
            if action in ('comment'):
                indent = ' ' * level * indent_size
                if elem.text:
                    text_list = elem.text.split('\n')
                    if len(text_list) == 1:
                        text = repr(elem.text)
                    else: # len(text_list) > 1
                        # format and join all non-empty lines
                        text = '\n' + ''.join(
                                ['{indent}{content}\n'.format(
                                        indent=' '*(len(t)-len(t.lstrip())),
                                        content=repr(t.strip() + ' ')
                                    ) for t in text_list if len(t.strip())>0
                                ]
                            ) + indent
                else:
                    text = ''
                if level == 0:
                    # store the comment so that it can be appended later
                    if main_element_processed_flag:
                        posterior_list.append("{indent}etree.Comment({comment})".format(
                            indent = indent,
                            comment = text,
                        ))
                    else:
                        previous_list.append("{indent}etree.Comment({comment})".format(
                            indent = indent,
                            comment = text,
                        ))
                else:
                    output.write("{indent}etree.Comment({comment}),\n".format(
                        indent = indent,
                        comment = text,
                    ))
            elif action in ('start'):
                main_element_processed_flag = True
                if last_action == None:
                    indent = ''
                else:
                    indent = ' ' * level * indent_size
                level += 1
                if elem.text:
                    # METHOD 1
#                    # treat all text string the same. this works but gets
#                    # messy for multi-line test strings
#                    text = repr(elem.text)
                    # METHOD 2 - format multiline strings differently
                    text_list = elem.text.split('\n')
                    if len(text_list) == 1:
                        text = repr(elem.text)
                    else: # len(text_list) > 1
                        # format and join all non-empty lines
                        text = '\n' + ''.join(
                                ['{indent}{content}\n'.format(
                                        indent=' '*(len(t)-len(t.lstrip())),
                                        content=repr(t.strip() + ' ')
                                    ) for t in text_list if len(t.strip())>0
                                ]
                            ) + indent
                else:
                    text = ''
                output.write('{indent}{factory}.{tag}({text}\n'.format(
                    indent = indent,
                    factory = get_factory_object_name(namespace),
                    tag = element_name,
                    text = text,
                ))
            elif action in ('end'):
                level -= 1
                if last_action == 'start':
                    output.pos -= 1
                    indent = ''
                else:
                    indent = ' ' * level * indent_size
                for att,val in elem.items():
                    output.write('{0}  {1}="{2}",\n'.format(indent,att,val))
                output.write('{0}),\n'.format(indent))
        last_action = action
    
    # remove the last comma
    output.pos -= 2
    output.truncate()
    output.write('\n')
    
    for entry in previous_list:
        output.write('doc.addprevious({entry})\n'.format(
            entry=entry
        ))
    for entry in posterior_list:
        output.write('doc.addnext({entry})\n'.format(
            entry=entry
        ))
    
    # add python code to print out the KML document
    output.write('print etree.tostring(etree.ElementTree(doc),pretty_print=True)\n')
    
    contents = output.getvalue()
    output.close()
    return contents
Example #6
0
def write_python_script_for_kml_document(doc):
    "Generates a python script that will construct a given KML document"
    import StringIO
    from pykml.helpers import separate_namespace

    output = StringIO.StringIO()
    indent_size = 2

    # add the etree package so that comments can be handled
    output.write('from lxml import etree\n')

    # add the namespace declaration section
    output.write('from pykml.factory import KML_ElementMaker as KML\n')
    output.write('from pykml.factory import ATOM_ElementMaker as ATOM\n')
    output.write('from pykml.factory import GX_ElementMaker as GX\n')
    output.write('\n')

    level = 0
    xml = StringIO.StringIO(etree.tostring(doc))
    context = etree.iterparse(xml, events=("start", "end", "comment"))
    output.write('doc = ')
    last_action = None
    main_element_processed_flag = False
    previous_list = []  # list of comments before the root element
    posterior_list = []  # list of comments after the root element
    for action, elem in context:
        # TODO: remove the following redundant conditional
        if action in ('start', 'end', 'comment'):
            namespace, element_name = separate_namespace(elem.tag)
            if action in ('comment'):
                indent = ' ' * level * indent_size
                if elem.text:
                    text_list = elem.text.split('\n')
                    if len(text_list) == 1:
                        text = repr(elem.text)
                    else:  # len(text_list) > 1
                        # format and join all non-empty lines
                        text = '\n' + ''.join([
                            '{indent}{content}\n'.format(
                                indent=' ' * (len(t) - len(t.lstrip())),
                                content=repr(t.strip() + ' '))
                            for t in text_list if len(t.strip()) > 0
                        ]) + indent
                else:
                    text = ''
                if level == 0:
                    # store the comment so that it can be appended later
                    if main_element_processed_flag:
                        posterior_list.append(
                            "{indent}etree.Comment({comment})".format(
                                indent=indent,
                                comment=text,
                            ))
                    else:
                        previous_list.append(
                            "{indent}etree.Comment({comment})".format(
                                indent=indent,
                                comment=text,
                            ))
                else:
                    output.write("{indent}etree.Comment({comment}),\n".format(
                        indent=indent,
                        comment=text,
                    ))
            elif action in ('start'):
                main_element_processed_flag = True
                if last_action == None:
                    indent = ''
                else:
                    indent = ' ' * level * indent_size
                level += 1
                if elem.text:
                    # METHOD 1
                    #                    # treat all text string the same. this works but gets
                    #                    # messy for multi-line test strings
                    #                    text = repr(elem.text)
                    # METHOD 2 - format multiline strings differently
                    text_list = elem.text.split('\n')
                    if len(text_list) == 1:
                        text = repr(elem.text)
                    else:  # len(text_list) > 1
                        # format and join all non-empty lines
                        text = '\n' + ''.join([
                            '{indent}{content}\n'.format(
                                indent=' ' * (len(t) - len(t.lstrip())),
                                content=repr(t.strip() + ' '))
                            for t in text_list if len(t.strip()) > 0
                        ]) + indent
                else:
                    text = ''
                output.write('{indent}{factory}.{tag}({text}\n'.format(
                    indent=indent,
                    factory=get_factory_object_name(namespace),
                    tag=element_name,
                    text=text,
                ))
            elif action in ('end'):
                level -= 1
                if last_action == 'start':
                    output.pos -= 1
                    indent = ''
                else:
                    indent = ' ' * level * indent_size
                for att, val in elem.items():
                    output.write('{0}  {1}="{2}",\n'.format(indent, att, val))
                output.write('{0}),\n'.format(indent))
        last_action = action

    # remove the last comma
    output.pos -= 2
    output.truncate()
    output.write('\n')

    for entry in previous_list:
        output.write('doc.addprevious({entry})\n'.format(entry=entry))
    for entry in posterior_list:
        output.write('doc.addnext({entry})\n'.format(entry=entry))

    # add python code to print out the KML document
    output.write(
        'print etree.tostring(etree.ElementTree(doc),pretty_print=True)\n')

    contents = output.getvalue()
    output.close()
    return contents