Example #1
0
def get_xml_write2(classname, box, savepath):
    with open('template.xml', 'r') as fid:
        xml_str = fid.read()
    # xml_dict = xmldict.xml_to_dict(xml_str)['annotation']['object']
    xml_dict = xmldict.xml_to_dict(xml_str)
    del xml_dict['annotation']['object']
    objects = []
    for i in box:
        object = {}
        object['name'] = classname
        object['truncated'] = 0
        object['difficult'] = 0
        object['pose'] = 'Unspecified'
        bndbox = {
            'xmin': str(i[0]),
            'ymin': str(i[1]),
            'xmax': str(i[2]),
            'ymax': str(i[3])
        }
        object['bndbox'] = bndbox
        objects.append(object)
    # [x, y, x + w, y + h]
    xml_dict['annotation']['object'] = objects
    dict_xml = xmldict.dict_to_xml(xml_dict)

    dom = parseString(dict_xml).toprettyxml()

    with open(savepath, 'w') as f:
        f.write(dom)
        f.close()
Example #2
0
def get_xml_write(list_class, list_b, imagePath, savepath):
    with open('template.xml', 'r') as fid:
        xml_str = fid.read()
    # xml_dict = xmldict.xml_to_dict(xml_str)['annotation']['object']
    xml_dict = xmldict.xml_to_dict(xml_str)
    del xml_dict['annotation']['object']
    objects = []
    for i, v in enumerate(list_b):
        object = {}
        object['name'] = list_class[i]

        object['truncated'] = 0
        object['difficult'] = 0
        object['pose'] = 'Unspecified'
        bndbox = {
            'xmin': str(v[0]),
            'ymin': str(v[1]),
            'xmax': str(v[2]),
            'ymax': str(v[3])
        }
        object['bndbox'] = bndbox
        objects.append(object)

    xml_dict['annotation']['object'] = objects
    dict_xml = xmldict.dict_to_xml(xml_dict)

    dom = parseString(dict_xml).toprettyxml()
    # print(xml_dict['annotation']['folder'])

    with open(savepath + '\\' + imagePath.replace('jpg', 'xml'), 'w') as f:
        f.write(dom)
        f.close()
Example #3
0
 def get_model_edit_str(self, form_model_fields, submission_values, project_name, form_code):
     # todo instead of using form_model fields, use xform to find the fields
     answer_dict, edit_model_dict = {'form_code': form_code}, {}
     formatted_field_values = convert_date_values(form_model_fields, self._format_field_answers_for(form_model_fields, submission_values))
     answer_dict.update(formatted_field_values)
     edit_model_dict.update({project_name: answer_dict})
     return xmldict.dict_to_xml(edit_model_dict)
Example #4
0
def get_xml_write1(classname, box, imagePath, savepath):
    with open('template.xml', 'r') as fid:
        xml_str = fid.read()
    # xml_dict = xmldict.xml_to_dict(xml_str)['annotation']['object']
    xml_dict = xmldict.xml_to_dict(xml_str)
    del xml_dict['annotation']['object']
    object = {}
    object['name'] = classname
    object['truncated'] = 0
    object['difficult'] = 0
    object['pose'] = 'Unspecified'
    bndbox = {
        'xmin': str(box[0]),
        'ymin': str(box[1]),
        'xmax': str(box[0] + box[2]),
        'ymax': str(box[1] + box[3])
    }
    object['bndbox'] = bndbox
    # [x, y, x + w, y + h]
    xml_dict['annotation']['object'] = object
    dict_xml = xmldict.dict_to_xml(xml_dict)

    dom = parseString(dict_xml).toprettyxml()

    with open(savepath + '\\' + imagePath.replace('jpg', 'xml'), 'w') as f:
        f.write(dom)
        f.close()
Example #5
0
 def test_dict_to_xml_attributes(self):
     dict_xml = {'messages': {
         'message': [{'@foo': 'bar1', 'baz': 'baz1', '#text': 'message1'},
                     {'@foo': 'bar2', 'baz': 'baz2', '#text': 'message2'}],
         'flag': True
     }}
     expected = '<messages><message foo="bar1"><baz>baz1</baz>message1</message><message foo="bar2"><baz>baz2</baz>message2</message><flag>true</flag></messages>'
     self.assertEqual(expected, dict_to_xml(dict_xml))
Example #6
0
 def test_dict_to_xml_attributes(self):
     dict_xml = {'messages': {
         'message': [{'@foo': 'bar1', 'baz': 'baz1', '#text': 'message1'},
                     {'@foo': 'bar2', 'baz': 'baz2', '#text': 'message2'}],
         'flag': True
     }}
     expected = '<messages><message foo="bar1"><baz>baz1</baz>message1</message><message foo="bar2"><baz>baz2</baz>message2</message><flag>true</flag></messages>'
     self.assertEqual(expected, dict_to_xml(dict_xml))
def _dict_to_xml(dict_to_convert):
    """
    Convert Python dict to XML
    :param dict_to_convert: Python dict to be converted (dict)
    :return: XML (string)
    """

    __logger__.debug("Converting to XML the Python dict: " + str(dict_to_convert))
    return xmldict.dict_to_xml(dict_to_convert)
Example #8
0
def _dict_to_xml(dict_to_convert):
    """
    Convert Python dict to XML
    :param dict_to_convert: Python dict to be converted (dict)
    :return: XML (string)
    """

    logger.debug("Converting to XML the Python dict: " + str(dict_to_convert))
    return xmldict.dict_to_xml(dict_to_convert)
Example #9
0
 def test_dict_to_xml_simple(self):
     dict_xml = {
         'transaction': {
             'amount': '100.00',
             'currency_code': 'USD'
         }
     }
     expected = '<transaction><amount>100.00</amount><currency_code>USD</currency_code></transaction>'
     self.assertEqual(expected, dict_to_xml(dict_xml))
Example #10
0
 def test_dict_to_xml_lists(self):
     dict_xml = {
         'messages': {
             'message': ['message1', 'message2'],
             'flag': True
         }
     }
     expected = '<messages><message>message1</message><message>message2</message><flag>true</flag></messages>'
     self.assertEqual(expected, dict_to_xml(dict_xml))
def _dict_to_xml(dict_to_convert):
    """
    Converts Python dict to XML
    :param dict_to_convert: Python dict to be converted (dict)
    :return: XML (string)
    """

    logger.debug("Converting Python dict to XML")
    return xmldict.dict_to_xml(dict_to_convert)
Example #12
0
    def dict_to_return_format(self,response,return_format,response_dict):
        
        if return_format =='table' :
            ''' Will return in table format'''
            to_do = "Call the table output formatter"
            global response_table
            response_table = '\n'
            response_table = response_table +'\t'.join(response_dict)+"\n"
            
            def get_table(value_to_convert):
                ''' This will parse the dictionary recusrsively and print as table format'''
                table_data = ""
                if type(value_to_convert) == dict :
                    table_data = table_data +'\t'.join(value_to_convert)+"\n"
                    for temp_val in value_to_convert.values() :
                        table_data = table_data + get_table(temp_val)
                else :
                    table_data = table_data + str(value_to_convert) +"\t"
                return table_data 
            
            for value in response_dict.values() :
                response_table =  response_table + get_table(value)
                

                
            #response_table = response_table + '\t'.join(response_dict.values())
                
            return response_table
        
        elif return_format =='config':
            ''' Will return in config format'''
            to_do = 'Call dict to config coverter'
            response_string = str(response_dict)
            print response_string
            response_config = re.sub(",", "\n\t", response_string)
            response_config = re.sub("u\'", "\'", response_config)
            response_config = re.sub("{", "", response_config)
            response_config = re.sub("}", "\n", response_config)
            response_config = re.sub(":", " =", response_config)
            return "[response]\n\t "+response_config
            
        elif return_format == 'xml':
            ''' Will return in xml format'''
            from core import dicttoobject
            response_xml = xmldict.dict_to_xml(response_dict)
            response_xml = re.sub(">\s*<", ">\n<", response_xml)
            return "\n"+response_xml
        
        elif return_format == 'json':
            ''' Will return in json format'''
            to_do = 'Call dict to xml coverter'
            import json
            response_json = json.dumps(response_dict)
            return response_json
Example #13
0
    def dict_to_return_format(self,response,return_format,response_dict):
        
        if return_format =='table' :
            ''' Will return in table format'''
            to_do = "Call the table output formatter"
            global response_table
            response_table = '\n'
            response_table = response_table +'\t'.join(response_dict)+"\n"
            
            def get_table(value_to_convert):
                ''' This will parse the dictionary recusrsively and print as table format'''
                table_data = ""
                if type(value_to_convert) == dict :
                    table_data = table_data +'\t'.join(value_to_convert)+"\n"
                    for temp_val in value_to_convert.values() :
                        table_data = table_data + get_table(temp_val)
                else :
                    table_data = table_data + str(value_to_convert) +"\t"
                return table_data 
            
            for value in response_dict.values() :
                response_table =  response_table + get_table(value)
                

                
            #response_table = response_table + '\t'.join(response_dict.values())
                
            return response_table
        
        elif return_format =='config':
            ''' Will return in config format'''
            to_do = 'Call dict to config coverter'
            response_string = str(response_dict)
            print response_string
            response_config = re.sub(",", "\n\t", response_string)
            response_config = re.sub("u\'", "\'", response_config)
            response_config = re.sub("{", "", response_config)
            response_config = re.sub("}", "\n", response_config)
            response_config = re.sub(":", " =", response_config)
            return "[response]\n\t "+response_config
            
        elif return_format == 'xml':
            ''' Will return in xml format'''
            from core import dicttoobject
            response_xml = xmldict.dict_to_xml(response_dict)
            response_xml = re.sub(">\s*<", ">\n<", response_xml)
            return "\n"+response_xml
        
        elif return_format == 'json':
            ''' Will return in json format'''
            to_do = 'Call dict to xml coverter'
            import json
            response_json = json.dumps(response_dict)
            return response_json
Example #14
0
 def to_string(self, data):
     serialize_data_dict = {}
     for k, v in data.viewitems():
         if isinstance(v, (list, tuple, set)):
             v = {self.ITEM_TAG: v}
         elif isinstance(v, str):
             v = v.decode('utf-8')
         serialize_data_dict[k] = v
     return xmldict.dict_to_xml({
         'root': serialize_data_dict
     })
Example #15
0
 def test_dict_to_xml_attributes(self):
     dict_xml = {
         "messages": {
             "message": [
                 {"@foo": "bar1", "baz": "baz1", "#text": "message1"},
                 {"@foo": "bar2", "baz": "baz2", "#text": "message2"},
             ],
             "flag": True,
         }
     }
     expected = '<messages><message foo="bar1"><baz>baz1</baz>message1</message><message foo="bar2"><baz>baz2</baz>message2</message><flag>true</flag></messages>'
     self.assertEqual(expected, dict_to_xml(dict_xml))
Example #16
0
    def test_dict_to_xml(self):
        dict_xml = {'transaction': {'amount': '100.00', 'currency_code': 'USD'}}
        expected = '<transaction><amount>100.00</amount><currency_code>USD</currency_code></transaction>'
        self.assertEqual(expected, dict_to_xml(dict_xml))

        dict_xml = {'xml': {'foo': 'bar','baz': ['baz1', 'baz2'], 'flag': True}}
        expected = '<xml><flag>true</flag><foo>bar</foo><baz>baz1</baz><baz>baz2</baz></xml>'
        self.assertEqual(expected, dict_to_xml(dict_xml))

        dict_xml = {'xml': 
            {'foo': 'bar', 'baz': [
                {'baz1': 'baz2'}, 
                {'baz1':'baz2', '@baz':'baz'},
                {'baz3': {'@baz3':'baz3', '#text':'bazbaz'}}
            ], 
            '@qux': 'qux', 
            'doo': {'@doo1': 'doo1', '#text': 'doodoo'}
            }
        }
        expected = '<xml qux="qux"><foo>bar</foo><baz><baz1>baz2</baz1></baz><baz baz="baz"><baz1>baz2</baz1></baz><baz><baz3 baz3="baz3">bazbaz</baz3></baz><doo doo1="doo1">doodoo</doo></xml>'
        self.assertEqual(expected, dict_to_xml(dict_xml))
Example #17
0
    def test_xml_to_dict_and_reverse(self):

        test = '''<messages>
<message id="1">
a
b
...
</message>
<message id="2">
c
d
...
</message>
</messages>'''

        expected = {
            'messages': {
                'message': [
                    {
                        '@id': '1',
                        '#value': 'a\nb\n...',
                        '#text': '\na\nb\n...\n',
                    },
                    {
                        '@id': '2',
                        '#value': 'c\nd\n...',
                        '#text': '\nc\nd\n...\n',
                    },
                ]
            }
        }

        self.assertEqual(expected, xml_to_dict(test, strict=True))

        # once converted to dict, go back to xml (do not care about extra blanks)
        def _remove_blanks(content):

            from lxml import etree
            parser = etree.XMLParser(remove_blank_text=True)
            elem = etree.XML(content, parser=parser)
            return etree.tostring(elem)

        self.assertEqual(_remove_blanks(test), dict_to_xml(expected))
Example #18
0
    def test_xml_to_dict_and_reverse(self):

        test = '''<messages>
<message id="1">
a
b
...
</message>
<message id="2">
c
d
...
</message>
</messages>'''

        expected = {'messages':
                     {'message':
                        [
                            {'@id': '1',
                             '#value': 'a\nb\n...',
                             '#text': '\na\nb\n...\n',
                            },
                            {'@id': '2',
                             '#value': 'c\nd\n...',
                             '#text': '\nc\nd\n...\n',
                            },
                        ]
                    }
                  }

        self.assertEqual(expected, xml_to_dict(test, strict=True))

        # once converted to dict, go back to xml (do not care about extra blanks)
        def _remove_blanks(content):

            from lxml import etree
            parser = etree.XMLParser(remove_blank_text=True)
            elem = etree.XML(content, parser=parser)
            return etree.tostring(elem)

        self.assertEqual(_remove_blanks(test), dict_to_xml(expected))
Example #19
0
 def test_dict_to_xml_simple(self):
     dict_xml = {'transaction': {'amount': '100.00', 'currency_code': 'USD'}}
     expected = '<transaction><amount>100.00</amount><currency_code>USD</currency_code></transaction>'
     self.assertEqual(expected, dict_to_xml(dict_xml))
Example #20
0
 def test_dict_to_xml_lists(self):
     dict_xml = {"messages": {"message": ["message1", "message2"], "flag": True}}
     expected = "<messages><message>message1</message><message>message2</message><flag>true</flag></messages>"
     self.assertEqual(expected, dict_to_xml(dict_xml))
Example #21
0
 def get_xml(self):
     result = {'id': self._id}
     result.update(self.getDict())
     return dict_to_xml(result)
Example #22
0
def dict_to_xml(dict):
    return xmldict.dict_to_xml(dict)
Example #23
0
def dic_to_xml(dic):
    return xmldict.dict_to_xml(dic)
Example #24
0
def dict_to_xml(dict_to_convert):

    return xmldict.dict_to_xml(dict_to_convert)
 def convert(self):
     return xmldict.dict_to_xml(open(self.filename))
Example #26
0
def convert_dict_xml(dictionary):
    elem = dict_to_xml(dictionary)
    assert len(elem) == 1
    return ET.tostring(elem[0])
Example #27
0
 def test_dict_to_xml_empty(self):
     dict_xml = {'messages': {'message': None}}
     expected = '<messages><message>null</message></messages>'
     self.assertEqual(expected, dict_to_xml(dict_xml))
Example #28
0
 def format(self, value):
     obj = IOpenCollaborationServiceXML(value)()
     return '<?xml version="1.0"?>' + xmldict.dict_to_xml(obj)
def create_report(bulletin_reports, file_name):
    from xmldict import dict_to_xml
    xml = dict_to_xml({file_name: bulletin_reports})
    f_ptr = open(__base_path + file_name + ".xml", "w")
    f_ptr.write(xml)
    f_ptr.close()
Example #30
0
 def test_dict_to_xml_lists(self):
     dict_xml = {'messages': {'message': ['message1', 'message2'], 'flag': True}}
     expected = '<messages><message>message1</message><message>message2</message><flag>true</flag></messages>'
     self.assertEqual(expected, dict_to_xml(dict_xml))
Example #31
0
 def test_dict_to_xml_empty(self):
     dict_xml = {"messages": {"message": None}}
     expected = "<messages><message>null</message></messages>"
     self.assertEqual(expected, dict_to_xml(dict_xml))
Example #32
0
 def get_xml(self):
     result = {'id' : self._id}
     result.update(self.getDict())   
     return dict_to_xml(result)
Example #33
0
 def test_dict_to_xml_empty(self):
     dict_xml = {'messages': {'message': None}}
     expected = '<messages><message>null</message></messages>'
     self.assertEqual(expected, dict_to_xml(dict_xml))
Example #34
0
 def test_dict_to_xml_simple(self):
     dict_xml = {"transaction": {"amount": "100.00", "currency_code": "USD"}}
     expected = "<transaction><amount>100.00</amount><currency_code>USD</currency_code></transaction>"
     self.assertEqual(expected, dict_to_xml(dict_xml))