如何使用 Python 设置 XML 元素的属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18796280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:52:38  来源:igfitidea点击:

How do I set attributes for an XML element with Python?

pythonxmlpython-2.7elementtree

提问by Venkatesh

I am using ElementTree to build an XML file.

我正在使用 ElementTree 构建一个 XML 文件。

When I try to set an element's attribute with ET.SubElement().__setattr__(), I get the error AttributeError: __setattr__.

当我尝试使用 设置元素的属性时ET.SubElement().__setattr__(),出现错误AttributeError: __setattr__

import xml.etree.cElementTree as ET
summary = open(Summary.xml, 'w')
root = ET.Element('Summary')
ET.SubElement(root, 'TextSummary')
ET.SubElement(root,'TextSummary').__setattr__('Status','Completed') # Error occurs here
tree = ET.ElementTree(root) 
tree.write(summary)
summary.close()

After code execution, my XML should resemble the following:

代码执行后,我的 XML 应类似于以下内容:

<Summary>
    <TextSummary Status = 'Completed'/>
</Summary>

How do I add attributes to an XML element with Python using xml.etree.cElementTree?

如何使用 Python 向 XML 元素添加属性xml.etree.cElementTree

采纳答案by Thomas Orozco

You should be doing:

你应该这样做:

ET.SubElement(root,'TextSummary').set('Status','Completed')

The Etree documentation shows usage.

Etree文档显示使用

回答by Stevoisiak

You can specify attributes for an Elementor SubElementduring creation with keyword arguments.

您可以使用关键字参数在创建过程中为Element或指定属性SubElement

import xml.etree.ElementTree as ET

root = ET.Element('Summary')
ET.SubElement(root, 'TextSummary', Status='Completed')

XML:

XML:

<Summary>
    <TextSummary Status="Completed"/>
</Summary>


Alternatively, you can use .setto add attributes to an existing element.

或者,您可以使用.set向现有元素添加属性。

import xml.etree.ElementTree as ET

root = ET.Element('Summary')
sub = ET.SubElement(root, 'TextSummary')
sub.set('Status', 'Completed')

XML:

XML:

<Summary>
    <TextSummary Status="Completed"/>
</Summary>


Technical Explanation:

技术说明:

The constructors for Elementand SubElementinclude **extra, which accepts attributes as keyword arguments.

ElementSubElementinclude的构造函数**extra,它接受属性作为关键字参数。

xml.etree.ElementTree.Element(tag, attrib={}, **extra)
xml.etree.ElementTree.SubElement(parent, tag, attrib={}, **extra)

This allows you to add an arbitrary number of attributes.

这允许您添加任意数量的属性。

root = ET.Element('Summary', Date='2018/07/02', Timestamp='11:44am')
# <Summary Date = "2018/07/02" Timestamp = "11:44am">

You can also use use .setto add attributes to a pre-existing element. However, this can only add one element at a time. (As suggested by Thomas Orozco).

您还可以使用 use.set向预先存在的元素添加属性。但是,这一次只能添加一个元素。(正如托马斯·奥罗斯科Thomas Orozco所建议的那样)。

root = ET.Element('Summary')
root.set('Date', '2018/07/02')
root.set('Timestamp', '11:44am')
# <Summary Date = "2018/07/02" Timestamp = "11:44am">


Full Example:

完整示例:

import xml.etree.ElementTree as ET

root = ET.Element('school', name='Willow Creek High')
ET.SubElement(root, 'student', name='Jane Doe', grade='9')
print(ET.tostring(root).decode())
# <school name="Willow Creek High"><student grade="9" name="Jane Doe" /></school>

回答by Parveen Kaloi

The best way to set multiple attributes in single line is below. I wrote this code for SVG XML creation:

在单行中设置多个属性的最佳方法如下。我为 SVG XML 创建编写了以下代码:

from xml.etree import ElementTree as ET

svg = ET.Element('svg', attrib={'height':'210','width':'500'})
g = ET.SubElement(svg,'g', attrib={'x':'10', 'y':'12','id':'groupName'})
line = ET.SubElement(g, 'line', attrib={'x1':'0','y1':'0','x2':'200','y2':'200','stroke':'red'})

print(ET.tostring(svg, encoding="us-ascii", method="xml"))