【发布时间】:2014-11-06 13:56:59
【问题描述】:
我使用 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? (不推荐使用)?
【问题讨论】:
-
SubElement(parent,tag,attrib={name:key})语法对我来说很好用(Python 2.7.5)。您能否针对一个简短的两级 XML 文档、确切的插入代码和生成的 XML 输出提供一个示例? -
正如在下面的评论中发布的,我现在可以通过 doint subi.attrib 获得结果。不知何故,root[index].attrib 确实失败了......
标签: python attributes lxml elementtree