如何在不使用任何库的情况下生成xml文件?

时间:2020-08-31 10:55:26

标签: python xml parsing

我有一个唯一ID的列表,例如:ID = [123,455,786,234,788] 我有评论列表= ['hello world','this is true','earth is a sphere','please'] 以及列出评论发表日期的另一个列表。

2 个答案:

答案 0 :(得分:1)

python内置了xml支持。

import xml.etree.ElementTree as ET                                                                                                                            

country_data_as_string = '''<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>
'''


root = ET.fromstring(country_data_as_string)
print(root.tag)

此示例摘自documentation

答案 1 :(得分:0)

下面(使用伪数据)

import xml.etree.ElementTree as ET 

data = [{'name':'jack','car_color':'green'},{'name':'ben','car_color':'pink'}]

root = ET.Element('persons')
for entry in data:
    person = ET.SubElement(root, 'person')
    name = ET.SubElement(person, 'name')
    name.text = entry['name']
    color = ET.SubElement(person, 'car_color')
    color.text = entry['car_color']
ET.dump(root)

输出

<?xml version="1.0" encoding="UTF-8"?>
<persons>
   <person>
      <name>jack</name>
      <car_color>green</car_color>
   </person>
   <person>
      <name>ben</name>
      <car_color>pink</car_color>
   </person>
</persons>