【问题标题】:Python3 lxml builderPython3 lxml 构建器
【发布时间】:2016-04-20 13:17:12
【问题描述】:

我正在尝试使用下面的 python lxml builder lke 创建 XML 文件:

<entityset>
  <entity>
    <temp code="1stCode"/>
      <attr code="2ndCode">
        <value>PythonIsFun</value>
      </attr>
      <attr code="3rdCode">
        <value>PythonIsStillFun</value>
      </attr>
  </entity>
</entityset>

我的尝试:

import lxml.builder as lb

def generate_xml(temp_code, value, value2):

    temp = lb.E.entityset(
        lb.E.entity(
            lb.E.temp(code='{0}'.format(temp_code)),
            lb.E.attr(code='2ndCode'),
            lb.E.value('{0}'.format(value)),
            lb.E.attr(code='3rdCode'),
            lb.E.value('{0}'.format(value2))
        )
    )
    print(etree.tounicode(temp, pretty_print=True))

generate_xml('1stCode', 'PythonIsFun', 'PythonIsStillFun')

输出:

<entityset>
  <entity>
    <temp code="1stCode"/>
    <attr code="2ndCode"/>
    <value>PythonIsFun</value>
    <attr code="3rdCode"/>
    <value>PythonIsStillFun</value>
    <attribute/>
  </entity>
</entityset>

问题是我不知道如何在&lt;attr code="code here"&gt; &lt;/attr&gt; 标签之间添加&lt;value&gt; &lt;/value&gt; 元素。有没有办法使用 lxml 元素生成器来做到这一点?

【问题讨论】:

    标签: xml python-3.x lxml


    【解决方案1】:

    只需将lb.E.value() 移动为lb.E.attr() 的参数即可:

    temp = lb.E.entityset(
            lb.E.entity(
                lb.E.temp(code='{0}'.format(temp_code)),
                lb.E.attr(lb.E.value('{0}'.format(value)), code='2ndCode'),
                lb.E.attr(lb.E.value('{0}'.format(value2)), code='3rdCode'),
            )
        )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-02
      • 1970-01-01
      • 2011-12-16
      • 2020-03-24
      • 2015-02-14
      • 2016-07-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多