如何向ElementTree(Python)中的子元素添加属性

2024-04-29 08:31:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用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'

但是

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?(哪一个会被取消)?


Tags: thenode属性节点rootxmlwillsubelement