Open deepakganesh78 opened 2 weeks ago
import xml.etree.ElementTree as ET
def parse_xml(file_path): try: tree = ET.parse(file_path) root = tree.getroot() print("XML file parsed successfully.") return root except ET.ParseError as e: print(f"Error parsing XML: {e}") return None
file_path = 'your_xml_file.xml'
root = parse_xml(file_path)
if root is not None: print(f"Root tag: {root.tag}") print(f"Attributes: {root.attrib}")
# Define your classes and parsing logic
class Item:
def __init__(self, simple_type_name, category, partition, order_subtypes, specifics):
self.simple_type_name = simple_type_name
self.category = category
self.partition = partition
self.order_subtypes = order_subtypes
self.specifics = specifics
def __repr__(self):
return f'Item({self.simple_type_name}, {self.category}, {self.partition}, {self.order_subtypes}, {self.specifics})'
class Group:
def __init__(self, simple_type_name, category, order_subtypes, components):
self.simple_type_name = simple_type_name
self.category = category
self.order_subtypes = order_subtypes
self.components = components
def __repr__(self):
return f'Group({self.simple_type_name}, {self.category}, {self.order_subtypes}, {self.components})'
# Function to parse items and groups from the XML
def parse_items_and_groups(element):
items = []
groups = []
for child in element:
print(f"Processing tag: {child.tag}")
if child.tag == 'ITEM':
specifics = {elem.tag: elem.text for elem in child}
item = Item(
simple_type_name=child.get('SimpleTypeName'),
category=child.get('CategoryOrItemParent'),
partition=child.get('partition'),
order_subtypes=child.get('OrderSubtypes'),
specifics=specifics
)
items.append(item)
elif child.tag == 'GROUP':
components = [comp.find('RelativeTypeName').text for comp in child.find('Sequence')]
group = Group(
simple_type_name=child.get('SimpleTypeName'),
category=child.get('CategoryOrGroupParent'),
order_subtypes=child.get('OrderSubtypes'),
components=components
)
groups.append(group)
return items, groups
items, groups = parse_items_and_groups(root)
# Output the parsed data
for item in items:
print(item)
for group in groups:
print(group)
else: print("Failed to parse the XML file.")
import xml.etree.ElementTree as ET
Function to parse the XML file and handle errors
def parse_xml(file_path): try: tree = ET.parse(file_path) root = tree.getroot() print("XML file parsed successfully.") return root except ET.ParseError as e: print(f"Error parsing XML: {e}") return None
Path to your XML file
file_path = 'your_xml_file.xml'
Parse the XML file
root = parse_xml(file_path)
Ensure that the root is parsed correctly
if root is not None: print(f"Root tag: {root.tag}") print(f"Attributes: {root.attrib}")
else: print("Failed to parse the XML file.")