【问题标题】:Django - How to loop xml tag in xmlDjango - 如何在 xml 中循环 xml 标签
【发布时间】:2016-02-08 07:28:37
【问题描述】:

我想从我的 html 表单中保存/更新我的 xml 文件。有几个选项我必须为一个属性键入许多数据。但我不知道在将数据保存在 xml 时如何循环数据。

例如,我想保存这样的属性

<keywords>
     <string>WFS</string>
     <string>WMS</string>
     <string>GEOSERVER</string>
</keywords>

但是当我点击提交按钮时,结果是这样的

<keywords>
    <string>WFS WMS GEOSERVER</string>
</keywords>

顺便说一句,我正在使用 ElementTree

【问题讨论】:

    标签: python xml django elementtree


    【解决方案1】:

    你可以做到this way

    keywords = ET.Element('keywords')
    for string_ in strings: # < -- your strings
        string = ET.SubElement(keywords, 'string')
        string.text = string_
    
    ET.dump(keywords)
    

    已测试

    >>> import xml.etree.ElementTree as ET
    >>> keywords = ET.Element('keywords')
    >>> strings = ['a', 'b', 'c']
    >>> for string_ in strings:
            string = ET.SubElement(keywords, 'string')
            string.text = string_
    
    >>> ET.dump(keywords)
    <keywords><string>a</string><string>b</string><string>c</string></keywords>
    >>> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-08
      • 1970-01-01
      • 2013-11-08
      • 1970-01-01
      • 2017-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多