动态生成xml使用python

时间:2016-10-21 07:28:12

标签: python xml

createxml.py

import xml.etree.ElementTree as ET

var3 = raw_input("Enter the root Element: \n")
root = ET.Element(var3)

no_of_rows1=input("Enter the number of sub root for XML files: - \n")

def printme():
    var4 = raw_input("Enter the sub root Element: \n")
    doc = ET.SubElement(root, var4)
    no_of_rows=input("Enter the number of Element for XML files: - \n")
   #print no_of_rows
    for num in range(0, no_of_rows):
         print num
         var = raw_input("Enter Element: - \n")
         var1 = raw_input("Enter Data: - \n")

         ET.SubElement(doc, var).text =var1
    return;
for num in range(0, no_of_rows1):    
    printme()

tree = ET.ElementTree(root)
file = raw_input("Enter File Name: - \n")
tree.write(file)

ET.ElementTree(root).write(file, encoding="utf-8",    xml_declaration=True)         
print "Xml file Created..!!"

上面是动态创建xml的脚本。但有一个问题,写入xml文件时显示错误。什么错误的代码?无论我在哪里从控制台给出输入它的名字nameError。

以下是我开始的输出

Enter the root Element: 
names
Enter the number of sub root for XML files: - 
2
Enter the sub root Element: 
name1
Enter the number of Element for XML files: - 
2
0
Enter Element: - 
fname
Enter Data: - 
mad
1
Enter Element: - 
lname
Enter Data: - 
deck
Enter the sub root Element: 
name2
Enter the number of Element for XML files: - 
2
0
Enter Element: - 
fname
Enter Data: - 
Don
1
Enter Element: - 
lname
Enter Data: - 
brad
Enter File Name: - 
new.xml

Traceback (most recent call last):
File "/home/cosmitude10/neon/createxmlpython/writexml.py", line 27, in    <module>
ET.ElementTree(root).write(file, encoding="utf-8",  xml_declaration=True)         
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 812, in write
write("<?xml version='1.0' encoding='%s'?>\n" % encoding)
TypeError: descriptor 'write' requires a 'file' object but received a 'str'

0 个答案:

没有答案