How do I check if a string is a valid XML in Python?
Alex K
alex k profile pic

To check if a string is a valid XML in Python, you can use thexml.etree.ElementTree module, which is part of Python's standard library. This module provides functionality to parse and manipulate XML data. Here's an example of how you can perform this check:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

import xml.etree.ElementTree as ET

def is_valid_xml(string):
    try:
   ET.fromstring(string)
   return True
    except ET.ParseError:
   return False

# Usage:
xml_string = input("Enter an XML string: ")
if is_valid_xml(xml_string):
    print("The string is a valid XML.")
else:
    print("The string is not a valid XML.")

In the above code, theis_valid_xml() function takes astring parameter representing the XML string to check. It attempts to parse the string using theET.fromstring() function. If the parsing is successful, it indicates that the string is a valid XML and the function returnsTrue. If anET.ParseError exception is raised, it means the string is not a valid XML, and the function returnsFalse. You can use theis_valid_xml() function by providing an XML string as an argument. It will check if the string is a valid XML by attempting to parse it usingET.fromstring(). The result is then printed accordingly. It's important to note that this approach checks the XML string's basic syntactical correctness. However, it does not verify the XML against a specific schema or DTD (Document Type Definition). If you need to validate XML against a schema or perform more complex XML validation, you may consider using additional libraries or tools specifically designed for XML validation, such aslxml orxmlschema. Also, keep in mind that this approach assumes that the XML string is well-formed. If the XML string is malformed, it may still raise an exception even though it is not valid XML.