Python如何构建xml文档

Jackey Python 731 次浏览 , 没有评论
# 如何构建xml文档
from xml.etree.ElementTree import Element, ElementTree, tostring

e = Element('Data')
e.set('name', 'abc')
e.text = '123'

e2 = Element('Row')
e3 = Element('Open')
e3.text = '8.80'
e2.append(e3)
print(tostring(e2))
e.text = None
e.append(e2)
print(tostring(e))

et = ElementTree(e)
et.write('demo2.xml')

import csv


# 生成xml文件
def csvToXml(fname):
    with open(fname, 'r', encoding='gbk') as f:
        reader = csv.reader(f)
        headers = next(reader)

        root = Element('Data')
        for row in reader:
            eRow = Element('Row')
            root.append(eRow)
            for tag, text in zip(headers, row):
                e = Element(tag)
                e.text = text
                eRow.append(e)
    return ElementTree(root)


et = csvToXml('test.csv')
et.write('test.xml')

 

发表评论

您的电子邮箱地址不会被公开。

Go