如何使用Python设置XML元素的属性? [英] How do I set attributes for an XML element with Python?
本文介绍了如何使用Python设置XML元素的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用ElementTree构建XML文件。
I am using ElementTree to build an XML file.
当我尝试通过 ET.SubElement()设置元素的属性时。__setattr__ ()
,出现错误 AttributeError:__setattr __
。
When I try to set an element's attribute with ET.SubElement().__setattr__()
, I get the error 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()
代码执行后,我的XML应该类似于以下内容:
After code execution, my XML should resemble the following:
<Summary>
<TextSummary Status = 'Completed'/>
</Summary>
如何使用 xml.etree使用Python向XML元素添加属性.cElementTree
?
推荐答案
您应该这样做:
ET.SubElement(root,'TextSummary').set('Status','Completed')
这篇关于如何使用Python设置XML元素的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文