2012-10-17 45 views
-1

可能重複的XML文件:
Creating a simple XML file using python創建使用Python

我想寫從Python中的XML文件。 的XML就像只以下格式:

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

我用Python寫的代碼中使用lxmletree但XML文件,我得到的是這樣的:

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

請讓我知道如何得到想要的格式

我的代碼:

import os 
import sys 

進口lxml.builder作爲磅 從LXML進口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> 
+7

告訴我們你的代碼 – root

+0

http://stackoverflow.com/questions/3605680/creating-a-simple-xml-file-using-python?rq=1 – nexoma

+0

這看起來像一個錯字:地址「ABCDEF 「 – guettli

回答

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> 
+0

如果不是打印名稱和地址的值,如果我傳遞一個變量,那麼格式會被更改。我得到類似 dasff user1705326

+0

editied我的老問題只.. – user1705326

+0

不,你不應該編輯你的舊問題,如果你有一個新的問題。 http://meta.stackexchange.com/questions/145773/can-i-replace-an-old-question-by-editing-it你的原始問題已被正確回答。 – root