代码之家  ›  专栏  ›  技术社区  ›  Joshkunz

生成XML的最佳方法?[复制品]

  •  65
  • Joshkunz  · 技术社区  · 15 年前

    这个问题已经有了答案:

    我正在创建一个Web API,需要一种很好的方法快速生成一些格式良好的XML。我在python中找不到任何好的方法来做这个。

    注意:有些库看起来很有前途,但要么缺少文档,要么只输出到文件。

    6 回复  |  直到 15 年前
        1
  •  87
  •   Community Mohan Dere    12 年前

    lxml

    from lxml import etree
    
    # create XML 
    root = etree.Element('root')
    root.append(etree.Element('child'))
    # another child with text
    child = etree.Element('child')
    child.text = 'some text'
    root.append(child)
    
    # pretty string
    s = etree.tostring(root, pretty_print=True)
    print s
    

    <root>
      <child/>
      <child>some text</child>
    </root>
    

    tutorial

        2
  •  84
  •   Predelnik    9 年前

    ElementTree

    from xml.etree.ElementTree import Element, SubElement, tostring
    
    root = Element('root')
    child = SubElement(root, "child")
    child.text = "I am a child"
    
    print tostring(root)
    

    <root><child>I am a child</child></root>
    

    tutorial

    xmlTemplate = """<root>
        <person>
            <name>%(name)s</name>
            <address>%(address)s</address>
         </person>
    </root>"""
    
    data = {'name':'anurag', 'address':'Pune, india'}
    print xmlTemplate%data
    

    <root>
        <person>
            <name>anurag</name>
            <address>Pune, india</address>
         </person>
    </root>
    

        3
  •  15
  •   John Smith Optional    12 年前

    yattag

    from yattag import Doc
    
    doc, tag, text = Doc().tagtext()
    
    with tag('food'):
        with tag('name'):
            text('French Breakfast')
        with tag('price', currency='USD'):
            text('6.95')
        with tag('ingredients'):
            for ingredient in ('baguettes', 'jam', 'butter', 'croissants'):
                with tag('ingredient'):
                    text(ingredient)
    
    
    print(doc.getvalue())
    
        4
  •  14
  •   Lars Nordin    14 年前

    http://lxml.de/tutorial.html#the-e-factory

    import lxml.builder as lb
    from lxml import etree
    
    nstext = "new story"
    story = lb.E.Asset(
      lb.E.Attribute(nstext, name="Name", act="set"),
      lb.E.Relation(lb.E.Asset(idref="Scope:767"),
                name="Scope", act="set")
      )
    
    print 'story:\n', etree.tostring(story, pretty_print=True)
    

    story:
    <Asset>
      <Attribute name="Name" act="set">new story</Attribute>
      <Relation name="Scope" act="set">
        <Asset idref="Scope:767"/>
      </Relation>
    </Asset>
    
        5
  •  9
  •   SergO    11 年前

    ElementTree

    minidom

    from xml.dom import minidom
    
    doc = minidom.Document()
    
    root = doc.createElement('root')
    doc.appendChild(root)
    
    leaf = doc.createElement('leaf')
    text = doc.createTextNode('Text element with attributes')
    leaf.appendChild(text)
    leaf.setAttribute('color', 'white')
    root.appendChild(leaf)
    
    leaf_cdata = doc.createElement('leaf_cdata')
    cdata = doc.createCDATASection('<em>CData</em> can contain <strong>HTML tags</strong> without encoding')
    leaf_cdata.appendChild(cdata)
    root.appendChild(leaf_cdata)
    
    branch = doc.createElement('branch')
    branch.appendChild(leaf.cloneNode(True))
    root.appendChild(branch)
    
    mixed = doc.createElement('mixed')
    mixed_leaf = leaf.cloneNode(True)
    mixed_leaf.setAttribute('color', 'black')
    mixed_leaf.setAttribute('state', 'modified')
    mixed.appendChild(mixed_leaf)
    mixed_text = doc.createTextNode('Do not use mixed elements if it possible.')
    mixed.appendChild(mixed_text)
    root.appendChild(mixed)
    
    xml_str = doc.toprettyxml(indent="  ")
    with open("minidom_example.xml", "w") as f:
        f.write(xml_str)
    

    <?xml version="1.0" ?>
    <root>
      <leaf color="white">Text element with attributes</leaf>
      <leaf_cdata>
    <![CDATA[<em>CData</em> can contain <strong>HTML tags</strong> without encoding]]>  </leaf_cdata>
      <branch>
        <leaf color="white">Text element with attributes</leaf>
      </branch>
      <mixed>
        <leaf color="black" state="modified">Text element with attributes</leaf>
        Do not use mixed elements if it possible.
      </mixed>
    </root>
    
        6
  •  0
  •   Boa    9 年前

    web2py HTML helper objects

    standalone web2py module

    pip install web2py
    

    here

    here

    from gluon.html import *
    

    words = ['this', 'is', 'my', 'item', 'list']
    # helper function
    create_item = lambda idx, word: LI(word, _id = 'item_%s' % idx, _class = 'item')
    # create the HTML
    items = [create_item(idx, word) for idx,word in enumerate(words)]
    ul = UL(items, _id = 'my_item_list', _class = 'item_list')
    my_div = DIV(ul, _class = 'container')
    
    >>> my_div
    
    <gluon.html.DIV object at 0x00000000039DEAC8>
    
    >>> my_div.xml()
    # I added the line breaks for clarity
    <div class="container">
       <ul class="item_list" id="my_item_list">
          <li class="item" id="item_0">this</li>
          <li class="item" id="item_1">is</li>
          <li class="item" id="item_2">my</li>
          <li class="item" id="item_3">item</li>
          <li class="item" id="item_4">list</li>
       </ul>
    </div>