Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python,将嵌套元素添加到xml文件_Python_Xml Parsing_Elementtree - Fatal编程技术网

Python,将嵌套元素添加到xml文件

Python,将嵌套元素添加到xml文件,python,xml-parsing,elementtree,Python,Xml Parsing,Elementtree,我有这样一个xml文件: 我的项目名称 红色_嘈杂_蛇_0000.png 红蛇 未指明 未指明 未指明 618 774 1037 858 我需要添加另一个“对象”字段,类似于已经存在的字段。 我将各种值保存在变量中(因此,'name','pose','truncated','bndbox'中的值…),我只需要将其添加到原始xml文件中,这样在最后我应该得到如下结果: 红色\u嘈杂\u蛇-->更改的值 红色_嘈杂_蛇_0000.png 红蛇 未指明 0 0 618 774 1037 858

我有这样一个xml文件:


我的项目名称
红色_嘈杂_蛇_0000.png
红蛇
未指明
未指明
未指明
618
774
1037
858
我需要添加另一个“对象”字段,类似于已经存在的字段。 我将各种值保存在变量中(因此,'name','pose','truncated','bndbox'中的值…),我只需要将其添加到原始xml文件中,这样在最后我应该得到如下结果:


红色\u嘈杂\u蛇-->更改的值
红色_嘈杂_蛇_0000.png
红蛇
未指明
0
0
618
774
1037
858
-->添加的对象字段
儿童座椅
未指明
0
0
871
25
1190
566
我知道如何添加单个非嵌套元素,例如:

将xml.etree.ElementTree作为ET导入
in_file='error.xml'
tree=ET.parse(在_文件中)
root=tree.getroot()
##添加单个字段
add=ET.Element(“标签名称”)
add.tail='\n\t'
add.text='content'
根目录。插入(5,添加)
ET.dump(根目录)

但是我不知道如何正确地创建我需要的嵌套结构。

公平警告:不是每个人都喜欢这种方法-并且更喜欢手动构建元素-但是当涉及到冗长的嵌套节点结构时,我更喜欢使用这种类似模板的方法

#this assumes all your new variables are located in one list; if not - you'll have to modify
inserts = ["child_seat","Unspecified", 0, 0, 871, 25, 1190, 566]

new_el = f"\n<object>\n        \
<name>{inserts[0]}</name>\n        <pose>{inserts[1]}</pose>\n <truncated>{inserts[2]}</truncated>\n      \
<difficult>{inserts[3]}</difficult>\n        <bndbox>\n            <xmin>{inserts[4]}</xmin>\n           \
<ymin>{inserts[5]}</ymin>\n            <xmax>{inserts[6]}</xmax>\n    \
<ymax>{inserts[7]}</ymax>\n        </bndbox>\n </object>\n"

add = ET.fromstring(new_el)
root.insert(3,add)
print(ET.tostring(root).decode())
#假设所有新变量都位于一个列表中;如果没有-您将不得不修改
插入语=[“儿童座椅”,“未指定”,0,0,871,25,1190,566]
新建\u el=f“\n\n\
{inserts[0]}\n{inserts[1]}\n{inserts[2]}\n\
{inserts[3]}\n\n{inserts[4]}\n\
{inserts[5]}\n{inserts[6]}\n\
{插入[7]}\n\n\n“
add=ET.fromstring(新建)
根目录。插入(3,添加)
打印(ET.tostring(root.decode())

输出应该是您想要的。

我建议您将问题分为两个(或更多)问题;你很可能会得到这样的回答。谢谢,我在原来的问题中计算了部分内容,我删除了它,只留下了我还没有解决的部分!