I have a xml file for which I have to update a value of tag. Below is the content of the file
JavaScript
x
9
1
<annotation>
2
<folder>train</folder>
3
<filename>Arms1.jpg</filename>
4
<path>D:PyCharmWorkSpaceTensorflowworkspacetraining_demoimagestrainArms1.jpg</path>
5
<source>
6
<database>Unknown</database>
7
</source>
8
</annotation>
9
In the above content, I have to update the value of path
with new valueBelow is the code I have:
JavaScript
1
16
16
1
from bs4 import BeautifulSoup
2
import os
3
4
curr_dir = os.path.join(os.path.dirname(__file__), 'img')
5
files = os.listdir(curr_dir)
6
7
for file in files:
8
if ".xml" in file:
9
file_path = os.path.join(curr_dir, file)
10
with open(file_path, 'r') as f:
11
xml_data = f.read()
12
bs_data = BeautifulSoup(xml_data, "xml")
13
bs_data.path.string = "C:"
14
xml_file = open(file_path, "w")
15
xml_file.write(bs_data.prettify())
16
But its not getting updated in xml file. Can anyone please help. Thanks
Advertisement
Answer
Using ElementTree (no need for any external lib)
JavaScript
1
16
16
1
import xml.etree.ElementTree as ET
2
3
4
xml = '''<annotation>
5
<folder>train</folder>
6
<filename>Arms1.jpg</filename>
7
<path>D:PyCharmWorkSpaceTensorflowworkspacetraining_demoimagestrainArms1.jpg</path>
8
<source>
9
<database>Unknown</database>
10
</source>
11
</annotation>'''
12
13
root = ET.fromstring(xml)
14
root.find('path').text = 'new path value goes here'
15
ET.dump(root)
16
output
JavaScript
1
9
1
<annotation>
2
<folder>train</folder>
3
<filename>Arms1.jpg</filename>
4
<path>new path value goes here</path>
5
<source>
6
<database>Unknown</database>
7
</source>
8
</annotation>
9