2013-04-23 4 views
0

I가 다음 문자열 : python3에 대한 라이브러리에 내장 무엇 중첩 된 XML 데이터를 문자열로 변환

<?xml version="1.0" ?> 
<data> 
<country name = "Ireland"> 
    <region name = "Clare"> 
     <settlement name = "Boston"/> 
    </region> 
    <region name = "Cork"> 
     <settlement name = "Baltimore"/> 
     <settlement name = "Cobh"/> 
    </region> 
</country> 

<country name = "Sweden"> 
    <region name = "Dalarna"> 
     <settlement name = "Leksand"/> 
     <settlement name = "Mora"/> 
    </region> 
    <region name = "Västmanland"> 
     <settlement name = "Västerås"/> 
    </region> 
</country> 
</data> 

할하는 데 도움이 될 수 있습니다 다음과 같이 내가 XML로 변환 할

"Sweden, Västmanland, Västerås" 
"Sweden, Dalarna, Leksand" 
"Ireland, Cork, Cobh" 
"Ireland, Clare, Boston" 
"Ireland, Cork, Baltimore" 
"Sweden, Dalarna, Mora" 

이 변환은 내가 불필요하게 바퀴를 재발 명하게 만들었습니까? 다음과 같이

+2

유효하지 않은 XML 마크 업입니다. 속성이나 XML 텍스트를 사용해야 할 때, 속성 이름없이'='을 치는 것은 유효하지 않습니다. –

+3

이것은 다소 비 건설적인 질문입니다 (기본적으로 라이브러리와 접근 방식에 대한 제안을 요구하고 있습니다). 아직 아무 것도 시도하지 않았습니까? 어떤 문제가 발생 했습니까? –

+0

"정렬"은 XML에는 적용되지 않습니다. 당신이 그룹화하지 않는다면 말이야. –

답변

2
import xml.etree.ElementTree as ET 
from collections import defaultdict 

strings = ["Sweden, Västmanland, Västerås", 
"Sweden, Dalarna, Leksand", 
"Ireland, Cork, Cobh", 
"Ireland, Clare, Boston", 
"Ireland, Cork, Baltimore", 
"Sweden, Dalarna, Mora"] 

dd = defaultdict(lambda: defaultdict(list)) 

for s in strings: 
    a, b, c = s.split(', ') 
    dd[a][b].append(c) 

root = ET.Element('data') 

for c, regions in dd.items(): 
    country = ET.SubElement(root, 'country', {'name': c}) 
    for r, settlements in regions.items(): 
     region = ET.SubElement(country, 'region', {'name': r}) 
     for s in settlements: 
      settlement = ET.SubElement(region, 'settlement', {'name': s}) 


import xml.dom.minidom # just to pretty print for this example 
print(xml.dom.minidom.parseString(ET.tostring(root)).toprettyxml()) 

<?xml version="1.0" ?> 
<data> 
    <country name="Ireland"> 
     <region name="Cork"> 
      <settlement name="Cobh"/> 
      <settlement name="Baltimore"/> 
     </region> 
     <region name="Clare"> 
      <settlement name="Boston"/> 
     </region> 
    </country> 
    <country name="Sweden"> 
     <region name="Dalarna"> 
      <settlement name="Leksand"/> 
      <settlement name="Mora"/> 
     </region> 
     <region name="Västmanland"> 
      <settlement name="Västerås"/> 
     </region> 
    </country> 
</data> 
0

당신은 사전에 입력을 구문 분석 할 수 있습니다 : 이제

Sweden {'Vastmanland': ['Vasteras'], 'Dalarna': ['Leksand', 'Mora']} 
Ireland {'Clare': ['Boston'], 'Cork': ['Cobh', 'Baltimore']} 

쉽게이 DICT을 변환 할 수 있습니다

strings = ["Sweden, Vastmanland, Vasteras", 
"Sweden, Dalarna, Leksand", 
"Ireland, Cork, Cobh", 
"Ireland, Clare, Boston", 
"Ireland, Cork, Baltimore", 
"Sweden, Dalarna, Mora" ] 

d = {} 
for s in strings: 
    tmp = s.split(", ") 
    country = tmp[0].strip() 
    region = tmp[1].strip() 
    settlement = tmp[2].strip() 

    if d.get(country): 
     if d[country].get(region): 
      d[country][region].append(settlement) 
     else: 
      d[country][region] = [settlement] 
    else: 
     d[country] = {region: [settlement]} 

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

이 다음과 같은 출력을 제공합니다 ~ xml 문자열.

비록 jamylak의 답변이 나아졌지만.