I'm newish to coding and I've ran into a problem that I haven't been able to find a solution to.
I have some code that prompts the user to pick a directory and an XML file that it will parse and say whether the XML file is well-formed or not.
However, when the XML is malformed, I get an error and the program stops.
What I expect to happen is that the except will catch the parse error.
When I'm debugging, I can continue past the error and the rest of the code executes.
Here is the error:
Exception has occurred: ParseError
mismatched tag: line 306, column 14
File "C:\Users\user\project\SimpleXMLParseExcept.py", line 10, in <module>
tree = ET.parse(filepath)
xml.etree.ElementTree.ParseError: mismatched tag: line 306, column 14
Here is my code:
import os
import xml.etree.ElementTree as ET
directory = input("Enter the directory path: ")
filename = input("Enter the file name in the directory: ")
filepath = os.path.join(directory, filename)
try:
tree = ET.parse(filepath)
print(f"{filename} is a well-formed XML.")
except ET.ParseError as e:
print(f"{filename} is not a well-formed XML: {e}")
# Add a print statement to see if the exception is being caught
print("Exception caught by the try-except block.")