Python How To Order Xml File According To Csv Ordering?
I have this XML File:- final.xml
Solution 1:
One possible approach would be to use BeautifulSoup to help with the XML parsing. This can be installed using:
pip install beautifulsoup4
The code:
from bs4 import BeautifulSoup
import csv
import glob
tests = {}
# Read in the XML files and parse themfor xml_filename in glob.glob('*.xml'):
print(f'Parsing {xml_filename}')
withopen(xml_filename) as f_input:
soup = BeautifulSoup(f_input, 'xml')
# Store all test tags in a dictionary # (this assumes each test has a unique name)for test in soup.find_all('Test'):
tests[test['Name']] = test
# Locate the children tag and empty it
children = soup.find('Children')
children.clear()
# Read in the ordering CSV and append the tests in the required order into# the children tagwithopen('order.csv', newline='') as f_order:
csv_order = csv.reader(f_order)
header = next(csv_order)
forid, test_name in csv_order:
try:
children.append(tests.pop(test_name))
except KeyError:
print(f"Test '{test_name}' not present")
# Add any remaining tests not listed in the CSVfor test in tests.values():
children.append(test)
# Write the modified xmlwithopen('output.xml', 'w') as f_output:
f_output.write(str(soup))
The indenting of the XML will be modified but the structure will be maintained. A "prettier" output style can be obtained by changing the output write to:
f_output.write(soup.prettify())
It first stores all of the tests in a Python dictionary from all of the XML files. Then whilst reading your ordering CSV file it uses pop to read each test back out of the dictionary and append it into the children tag. By using pop()
it also removes the test from the dictionary. Any tests left over in the dictionary (that were not in the ordering CSV) could then be added to the end (if needed).
Post a Comment for "Python How To Order Xml File According To Csv Ordering?"