0

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>
2
  • Use an XML parsing library, for example ElementTree. Commented Nov 20, 2021 at 8:40
  • This is called wellformedness checking, not validation. Validation in XML means checking that the contents of each element match the content permitted by a DTD or schema. Commented Nov 20, 2021 at 12:53

1 Answer 1

1

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")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.