import xml.etree.ElementTree as ET
var3 = raw_input("Enter the root Element: \n")
root = ET.Element(var3)
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")
def printme():
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_rows):
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..!!"
我想使用python动态创建xml。
如何创建多个子根?
我从控制台给出文件名,以便在xml中存储书面元素。它给出了这个错误:
TypeError: descriptor 'write' requires a 'file' object but received a 'str'
我该怎么办?
答案 0 :(得分:1)
你没有。来自用户的元素,但您没有使用它。 使用循环并从循环中获取用户的元素详细信息,如下所示:
import xml.etree.ElementTree as ET
try:
no_of_rows=int(input("Enter the number of Element for XML files: - \n"))
root = input("Enter the root Element: \n")
root_element = ET.Element(root)
for _ in range(1, no_of_rows):
tag = input("Enter Element: - \n")
value = input("Enter Data: - \n")
ET.SubElement(root_element, tag).text = value
tree = ET.ElementTree(root_element)
tree.write("filename.xml")
print("Xml file Created..!!")
except ValueError:
print("Value Error")
except:
print("Exception Occuured")
enter code here
我希望这是你想要实现的目标。
答案 1 :(得分:-1)
如果你想创建xml,你可以这样做:
from lxml import etree
try:
root_text = raw_input("Enter the root Element: \n")
root = etree.Element(root_text)
child_tag = raw_input("Enter the child tag Element: \n")
child_text = raw_input("Enter the child text Element: \n")
child = etree.Element(child_text )
child.text =child_text
root.append(child)
with open('file.xml', 'w') as f:
f.write(etree.tostring(root))
f.close()
except ValueError:
print("Occured Error")
或者,如果你想要动态长度,你只需使用for循环。