【问题标题】:How to create an xml attribute xml:id using Python?如何使用 Python 创建 xml 属性 xml:id?
【发布时间】:2016-04-05 07:43:55
【问题描述】:

我正在使用python创建xml文件,我需要创建一个这样的属性

<element xml:id="something"/> some text 

我专门使用了 lcml,因为我需要在唯一标记之后添加一些文本,而使用 DOM 无法做到这一点。如果使用 DOM 可以做到这一点,那就太好了。 我该怎么做?

【问题讨论】:

    标签: python python-2.7 xml-parsing


    【解决方案1】:

    要添加属性,您应该这样做:

    import xml.etree.cElementTree as ET
    ET.SubElement(root,'element').set('xml:id','something')
    

    添加文字:

    tree = ET.parse('country_data.xml')
    root = tree.getroot()
    for element in root.findall('element'):
        element.text = str("some text")
    tree.write('output.xml')
    

    Etree documentation 显示用法。

    【讨论】:

    【解决方案2】:

    你应该使用tail属性:

    etree_element.tail = ' some text'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-18
      • 2019-03-24
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多