Created
October 26, 2016 14:13
-
-
Save Paebbels/0a24ee8fbe2356f0562a6bdeb19b6c46 to your computer and use it in GitHub Desktop.
Read and validate a XML file with lxml in Python.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class foo: | |
@classmethod | |
def FromFile(cls, filePath): | |
if (not filePath.exists()): | |
raise PyIpxactException("File '{0!s}' not found.".format(filePath)) | |
from FileNotFoundError(str(filePath)) | |
try: | |
with filePath.open(encoding="utf-8") as fileHandle: | |
content = fileHandle.read() | |
content = bytes(bytearray(content, encoding='utf-8')) | |
except OSError as ex: | |
raise PyIpxactException("Couldn't open '{0!s}'.".format(filePath)) | |
from ex | |
os.chdir("../lib/schema") | |
schemaPath = Path("index.xsd") | |
try: | |
with schemaPath.open(encoding="utf-8") as fileHandle: | |
schema = fileHandle.read() | |
schema = bytes(bytearray(schema, encoding='utf-8')) | |
except OSError as ex: | |
raise PyIpxactException("Couldn't open '{0!s}'.".format(schemaPath)) | |
from ex | |
xmlParser = etree.XMLParser(remove_blank_text=True, encoding="utf-8") | |
schemaRoot = etree.XML(schema, xmlParser) | |
schemaTree = etree.ElementTree(schemaRoot) | |
xmlSchema = etree.XMLSchema(schemaTree) | |
documentRoot = etree.XML(content, xmlParser) | |
if (not xmlSchema.validate(documentRoot)): | |
raise PyIpxactException("The input IP-XACT file is not valid.") | |
rootTag = etree.QName(documentRoot.tag) | |
print(rootTag.localname) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment