我有两个文件夹,其中一个文件夹包含数千个图像,另一个文件夹具有相应的.xml文件。XML文件和图像名称相同(即2007.xml和2007.jpg)。现在,我想将图像名称(2007.jpg)添加到其相应的文件(2007.xml)中。.xml文件格式为:
<?xml version='1.0' encoding='ASCII'?>
<annotation>
<size>
<width>1820</width>
<height>940</height>
</size>
<object>
<name>Car</name>
<bndbox>
<xmin>74.0</xmin>
<ymin>509.0</ymin>
<xmax>236.0</xmax>
<ymax>609.0</ymax>
</bndbox>
</annotation>
我想添加新的SubElement
<?xml version='1.0' encoding='ASCII'?>
<annotation>
<filename>2007.jpg</filename>
<size>
<width>1820</width>
<height>940</height>
</size>
<object>
<name>Car</name>
<bndbox>
<xmin>74.0</xmin>
<ymin>509.0</ymin>
<xmax>236.0</xmax>
<ymax>609.0</ymax>
</bndbox>
</annotation>
我正在尝试这样:
import xml.etree.ElementTree as ET
import os
doc = ET.parse('00390.xml')
root = doc.getroot()
s = '/image/00390.jpg'
filename = (os.path.basename(s))
userElement = ET.Element("annotation")
newSub = ET.SubElement(userElement, "filename")
newSub.set(filename, '')
root.insert(0, newSub)
tree = ET.ElementTree(root)
tree.write(open('3.xml', 'w'), encoding = 'UTF-8')
接收到输出:<filename 00390.jpg=""/>
虽然输出应该是<filename>00390.jpg</filename>
我认为问题是使用newSub.set(),它需要3个输入参数。
您新问题的更新答案
import xml.etree.ElementTree as ET
import os
doc = ET.parse('00390.xml')
root = doc.getroot()
s = '/image/00390.jpg'
filename = (os.path.basename(s))
userElement = ET.Element("annotation")
newSub = ET.SubElement(userElement, "filename")
newSub.set(filename, '')#<----- *****
root.insert(0, newSub)
tree = ET.ElementTree(root)
tree.write(open('3.xml', 'w'), encoding = 'UTF-8')
此输出将返回
<filename 00390.jpg=""/>
代替
<filename>00390.jpg</filename>
这是因为在(*)处设置的是属性值,而不是XML子元素标记中的文本。
为您解决问题,替换该newSub.set(filename, '')
本
newSub.text = filename#Assigns text
root.insert(0,newSub)
#Returns this <filename>00390.jpg</filename>
在这里查看示例
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句