可能重复:
使用 python 创建一个简单的 XML 文件
我想用 Python 写一个 XML 文件。XML 仅类似于以下格式:
<Title rollid="1" mainid="1" teamid="1">
<s name="hello" address"abcdef" "etc"/>
<s name="" address="" />
</Title>
我用 Python 编写了代码,lxml
但是etree
我得到的 XML 文件是这样的:
<Title>
<s>rollid=""1" mainid="1"</s>
<s>name="" address=""</s>
<s>name="" address=""</s>
</Title>
请让我知道如何获得所需的格式
我的代码:
import os
import sys
从 lxml 导入 etree 导入 lxml.builder 作为 lb
#i made a dummy file AddDetail.xml with the root tags
def WriteDetails(rolid,mainid,name,address):
myhash=dict() # Declaring a dictionary
#Storing the data which has to be written to xml in a dictionary
myhash={'rollid':rolid, 'mainid':mainid, 'name':name, 'opid':opid, 'address':address}
# Converting the data from dictionary to string for XML and
also checking if any valueis 0
data=' '.join([('%s="%s"')%(key,value) for key,value in myhash.iteritems()if value])
# Creating the root Element
root=etree.Element("Title")
# Making a new Document Tree
doc=etree.parse('AddDetail.xml')
# Getting the root tag
root=doc.getroot()
# Adding a new Element
y=lab.E.Title(lb.E.s(data),
rollid="1" mainid="1" teamid="1")
print etree.tostring(y,pretty_print=true)
output i get is
<Title rollid="1" mainid="1" teamid="1">
<s>name="hello" address="aaaa"</s>
</Title>
I need something like
<Title rollid="1" mainid="1" teamid="1">
<s name="hello" address="aaaa"/>
</Title>