Home > Mobile >  XML validation using python
XML validation using python

Time:11-20

I am looking a python code which returns "XML is good" when each starting tag has corresponding matching ending tag in XML file and all <, >, / are present correctly. If starting tag has no corresponding matchin ending tag or if any of <, >, / is missing then code should return "XML is not good". I am new to xml, python. Thanks in advance.

Sample XML file

<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

CodePudding user response:

As @Thomas commented, you can parse the sample XML file with ElementTree, if you got ParseError then you would catch it by printing the message:

import xml.etree.ElementTree as ET
from xml.etree.ElementTree import ParseError
try:
    tree = ET.parse('s.xml')
    root = tree.getroot()
    print("XML is good")
except ParseError:
    print("XML is not good")
  • Related