Check if String is Valid XML using Python

xml.etree.ElementTree.fromstring function and error handling

import xml.etree.ElementTree as elementTree


def isXml(value):
    try:
        elementTree.fromstring(value)
    except elementTree.ParseError:
        return False
    return True


print(isXml('<persons><person><name>John</name></person></persons>'))
print(isXml('<value>1</value><value>2</value>'))

Leave a Comment

Cancel reply

Your email address will not be published.