使用Python创建XML文件

时间:2012-10-17 07:16:52

标签: python xml

  

可能重复:
  Creating a simple XML file using python

我想从Python编写一个XML文件。 XML仅与以下格式类似:

<Title rollid="1" mainid="1" teamid="1">
<s name="hello" address"abcdef" "etc"/>
 <s name="" address="" />
</Title>

我使用lxmletree在Python中编写代码,但我得到的XML文件是这样的:

<Title>
<s>rollid=""1" mainid="1"</s>
<s>name="" address=""</s>
<s>name="" address=""</s>
</Title>

请让我知道如何获得所需的格式

我的代码:

import os
import sys

将lxml.builder导入为lb     来自lxml import etree

#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>

2 个答案:

答案 0 :(得分:1)

您需要了解如何创建属性:

http://lxml.de/tutorial.html#elements-carry-attributes

>>> root = etree.Element("root", interesting="totally")
>>> etree.tostring(root)
b'<root interesting="totally"/>'

答案 1 :(得分:0)

使用lxml.builder,here's也是一个教程。

   import lxml.builder as lb
   from lxml import etree

y=lb.E.Title(lb.E.s(name="hello",adress="abcdef"),
             lb.E.s(name="",adress=""),
             rollid="1", mainid="1",teamid="1")

print etree.tostring(y, pretty_print=True)

>>> 
<Title teamid="1" rollid="1" mainid="1">
  <s adress="abcdef" name="hello"/>
  <s adress="" name=""/>
</Title>