【问题标题】:Creating an XML file using Python [duplicate]使用 Python 创建 XML 文件 [重复]
【发布时间】:2012-10-07 09:37:04
【问题描述】:

可能重复:
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 导入 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>

【问题讨论】:

标签: python xml


【解决方案1】:

你需要学习如何创建属性:

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

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

【讨论】:

    【解决方案2】:

    使用 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>
    

    【讨论】:

    • 如果不是打印姓名和地址的值,如果我传递一个变量,那么格式就会改变。我得到类似 dasff 的东西
    • 只编辑了我的旧问题..
    • 不,如果您有新问题,则不应编辑旧问题。 meta.stackexchange.com/questions/145773/…您的原始问题已正确回答。
    猜你喜欢
    • 2021-06-13
    • 2012-09-21
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    相关资源
    最近更新 更多