如何在 ElementTree (Python) 中向 SubElement 添加属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/25807414/
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
How do I add attributes to SubElement in ElementTree (Python)
提问by sibert
I successfully added a new node to an Element using PY's ElementTree. I now try to give it attributes, which fails, despite I'm following the tutorial.
我使用 PY 的 ElementTree 成功地向 Element 添加了一个新节点。我现在尝试给它赋予属性,但失败了,尽管我正在学习教程。
my example xml:
我的示例 xml:
<?xml version="1.0" encoding="UTF-8"?>
<xml>
<level01>
<level02>
<level03>
<level04>
<node q="3,4,5,7,8" p="zen"/>
<node q="a,s,e,o,l" p="zen"/>
</level04>
</level03>
# >> here will be the new node, called <subi/> <<   
<level03>
<level04>
<node q="x,y" p="zen"/>
<node q="xxx,yyy" p="zen"/>
</level04>
</level03>
</level02>
</level01>
</xml>
The node is created like this:
节点是这样创建的:
subi = ETL.SubElement(root[0][0][1][0][0], 'subi')
which works, it can then be accessed via root001000 and it's tag can be read.
哪个有效,然后可以通过 root001000 访问它并且可以读取它的标签。
but I fail trying to add attributes.
但我尝试添加属性失败。
I tried using the syntax I found in another thread here: (with my names ofc)
我尝试使用我在另一个线程中找到的语法:(以我的名字 ofc)
>>> myattributes = {"size": "small", "gender": "unknown"}
>>> child = ET.SubElement(parent, "child", attrib=myattributes, age="10" )
Also I tried it directly, like
我也直接试过了,比如
subi = ETL.SubElement(root[0][0][1][0][0], 'subi', attrib={"size": "small", "gender": "unknown"})
Results are always
结果总是
root[0][0][1][0][0][0].tag
'subi'
but
但
root[0][0][1][0][0][0].attrib
{}
I also found how lxml does it, but this does not work with elementtree
我还发现了 lxml 是如何做到的,但这不适用于 elementtree
#Any keyword arguments of the form name=value that you supply to the constructor are added #to the element's attributes. For example, this code:
newReed = etree.Element('reed', pitch='440', id='a4')
#will produce an element that looks like this:
<reed pitch='440' id='a4'/>
What am I doing wrong? How can I do it right? Is there a way to make elementtree do it? Or do I have to use lxml? (which would be dispreferred) ?
我究竟做错了什么?我怎样才能做对?有没有办法让 elementtree 做到这一点?还是我必须使用 lxml?(这将是不受欢迎的)?
采纳答案by German Petrov
Isn't this you are trying to do? Assuming that subiis your element and you can access it, you can further use ElementTreemethod set:
这不是你想要做的吗?假设这subi是您的元素并且您可以访问它,您可以进一步使用ElementTree方法set:
subi.set(attr, value)
Look here about setmethod of ElementTree: https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.set
看看这里的set方法ElementTree:https: //docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.set
回答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')
# <Summary><TextSummary Status="Completed" /></Summary>
Alternatively, you can use .setto add an attribute to an element after creation.
或者,您可以使用.set在创建后向元素添加属性。
import xml.etree.ElementTree as ET
root = ET.Element('Summary')
sub = ET.SubElement(root, 'TextSummary')
sub.set('Status', 'Completed')
# <Summary><TextSummary Status="Completed" /></Summary>
Generated XML:
生成的 XML:
<Summary>
    <TextSummary Status="Completed"/>
</Summary>
Explanation:
解释:
The constructors for Elementand SubElementinclude **extra, which accepts attributes as keyword arguments.
Element和SubElementinclude的构造函数**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. (Suggested by German Petrov).
您还可以使用 use.set向预先存在的元素添加属性。但是,这一次只能添加一个元素。(由德国彼得罗夫推荐)。
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>

