Skip to main content
 首页 » 编程设计

python之如何使用python在xml文件中插入一个带有属性的新标签

2025年05月04日9soundcode

我有一个如下所示的 xml 文件,我想在其中使用 python 脚本添加一个带有属性的标签。

<package>  
  <data>  
    <id>sample</id>  
    <version>1.1</version>  
  </data> 
  <files> 
   <file src = "C:/sample.txt"/> 
  </files> 
</package> 

我添加带有属性的标签的 python 脚本如下脚本,但它没有按照我的意愿添加标签:

import xml.etree.ElementTree as ET 
tree_A = ET.parse('test.xml') 
root_A= tree_A.getroot() 
print root_A[1].tag 
if root_A[1].tag is not None:     
    newNodeName = ET.Element('file src') 
    newNodeName.text ="D:/other.txt" 
    newNode.append(newNodeName) 
    root_A[1].insert(0,newNodeName) 
tree_A.write('test.xml') 

我得到的输出 xml 是:

<package>  
  <data>  
    <id>sample</id>  
    <version>1.1</version>  
  </data> 
  <files> 
   <file src = "C:/sample.txt"/> 
   ###i want following tag as <file src ="D:/other.txt"/> 
   <file src> D:/other.txt</file src>  
  </files> 
</package> 

那么,请建议我如何在 xml 文件中添加带有属性的标签?

请您参考如下方法:

您可以使用 ET.Element('file', {'src':'D:/other.txt'}) 构造名为 file 的元素名为 src 的属性。