我使用 PY 的 ElementTree 成功向元素添加了一个新节点。
我现在尝试赋予它属性,但失败了,尽管我正在遵循教程。
我的示例 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>
节点是这样创建的:
subi = ETL.SubElement(root[0][0][1][0][0], 'subi')
成功后,可以通过 root001000 访问它,并且可以读取它的标签。
但我尝试添加属性失败。
我尝试使用在另一个线程中找到的语法:(用我的名字ofc)
>>> myattributes = {"size": "small", "gender": "unknown"}
>>> child = ET.SubElement(parent, "child", attrib=myattributes, age="10" )
我也直接尝试过,比如
subi = ETL.SubElement(root[0][0][1][0][0], 'subi', attrib={"size": "small", "gender": "unknown"})
结果总是
root[0][0][1][0][0][0].tag
'subi'
but
root[0][0][1][0][0][0].attrib
{}
我还发现了 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'/>
我究竟做错了什么?我怎样才能做对呢?有没有办法让elementtree做到这一点?或者我必须使用 lxml 吗? (这将是不受欢迎的)?