2012-10-10 27 views
1

我有一個帶有值(字符串,列表,字典)的字典,我想將該字典轉換爲xml格式的字符串。將python字典轉換爲xml字符串而不使用內置函數

包含的值可能是子字典和列表(不是固定格式)。所以我想從字典中獲得所有的值,並且不使用像(import xml,ElementTree等)的任何內建函數來形成xml字符串。

例如:

輸入:

{'Employee':{ 'Id' : 'TA23434', 'Name':'Kesavan' , 'Email':'[email protected]' , 'Roles':[ {'Name':'Admin' ,'RoleId':'xa1234' },{'Name':'Engineer' , 'RoleId':'xa5678' }], 'Test':{'a':'A','b':'b'} }} 

輸出應該是:

<Employee> 
     <Id>TA23434</Id> 
     <Name>Kesaven</Name> 
     <Email>, ..... </Email> 
     <Roles> 
      <Roles-1> 
         <Name>Admin</Name> 
         <RoleId>xa1234</RoleId> 
      </Roles-1> 
      <Roles-2> 
         <Name>Admin</Name> 
         <RoleId>xa1234</RoleId> 
      </Roles-2> 
     <Roles> 
     <Test> 
      <a>A</a> 
     <b>B</b> 
     </Test> 
</Employee> 

任何人都可以建議對這個哪種方式是很容易這樣做。

+0

這是一個典型的家庭作業。請解釋你所嘗試的,然後我們可以幫助 – tback

+0

@tback請不要再使用'homework'標籤。它已被正式棄用。 – sloth

+0

@ Mr.Steak對不起,我不知道。不會再使用它。 – tback

回答

1

你可以使用這樣的事情:

def to_tag(k, v): 
    """Create a new tag for the given key k and value v""" 
    return '<{key}>{value}<{key}/>'.format(key=k, value=get_content(k, v)) 

def get_content(k, v): 
    """Create the content of a tag by deciding what to do depending on the content of the value""" 
    if isinstance(v, str): 
     # it's a string, so just return the value 
     return v 
    elif isinstance(v, dict): 
     # it's a dict, so create a new tag for each element 
     # and join them with newlines 
     return '\n%s\n' % '\n'.join(to_tag(*e) for e in v.items()) 
    elif isinstance(v, list): 
     # it's a list, so create a new key for each element 
     # by using the enumerate method and create new tags 
     return '\n%s\n' % '\n'.join(to_tag('{key}-{value}'.format(key=k, value=i+1), e) for i, e in enumerate(v)) 

d = {'Employee':{ 'Id' : 'TA23434', 'Name':'Kesavan' , 'Email':'[email protected]' , 'Roles':[ {'Name':'Admin' ,'RoleId':'xa1234' },{'Name':'Engineer' , 'RoleId':'xa5678' }], 'Test':{'a':'A','b':'b'} }} 

for k,v in d.items(): 
    print to_tag(k, v) 

我加了一些意見,但應清楚發生了什麼,它應該是足以讓你startet。

dict s在python中沒有排序,所以生成的XML也沒有排序。

結果:

<Employee> 
<Email>[email protected]<Email/> 
<Test> 
<a>A<a/> 
<b>b<b/> 
<Test/> 
<Id>TA23434<Id/> 
<Roles> 
<Roles-1> 
<RoleId>xa1234<RoleId/> 
<Name>Admin<Name/> 
<Roles-1/> 
<Roles-2> 
<RoleId>xa5678<RoleId/> 
<Name>Engineer<Name/> 
<Roles-2/> 
<Roles/> 
<Name>Kesavan<Name/> 
<Employee/> 
+0

謝謝牛排先生。我找到了另一種解決方法(遞歸方法)。 – keshavv