It is not possible to write a generic script that would handle ALL types of XML files, you will need to adapt the script for your own needs.
The following approach should get you started, it first finds all of the Metrics tags and builds up CSV rows from there using a standard csv.DictWriter().
from bs4 import BeautifulSoup
import csv
headers = [
"Scope",
"Project",
"Namespace",
"Type",
"Member",
"MaintainabilityIndex",
"CyclomaticComplexity",
"ClassCoupling",
"DepthOfInheritance",
"SourceLines",
"ExecutableLines",
]
namespace = ''
with open('input.xml') as f_input:
soup = BeautifulSoup(f_input.read(), "xml")
with open('output.csv', 'w', newline='') as f_output:
csv_output = csv.DictWriter(f_output, fieldnames=headers)
csv_output.writeheader()
for metrics in soup.find_all('Metrics'):
parent = metrics.parent
if parent.name == 'Namespace':
namespace = parent['Name']
elif parent.name == 'Method':
member = parent['Name']
else:
member = ''
row = {'Scope' : parent.name, 'Namespace' : namespace, 'Member' : member}
for metric in metrics.find_all('Metric'):
row[metric['Name']] = metric['Value']
csv_output.writerow(row)
This would give you an output.csv CSV file starting like:
Scope,Project,Namespace,Type,Member,MaintainabilityIndex,CyclomaticComplexity,ClassCoupling,DepthOfInheritance,SourceLines,ExecutableLines
Assembly,,,,,88,17,35,3,100,22
Namespace,,TEST,,,84,7,26,1,63,15
NamedType,,TEST,,,91,2,8,1,14,3
Method,,TEST,,void Program.Main(string[] args),93,1,3,,4,1
Method,,TEST,,IHostBuilder Program.CreateHostBuilder(string[] args),84,1,6,,6,2
NamedType,,TEST,,,78,5,19,1,43,12
Method,,TEST,,Startup.Startup(IConfiguration configuration),96,1,1,,4,1
Hopefully this helps to get you started. I made use of the xml parser as this does not convert all tags to lowercase.
tag.stringis still a bs4 object, trystr(tag.string)xml2csv(unicode(sys.argv[1]))withxml2csv("input.xml"). Please trim your code down as much as possible. You need to provide a proper minimal reproducible example. There are also indentation errors in the code in the question.