Skip to content

Instantly share code, notes, and snippets.

@Paebbels
Created October 26, 2016 14:13
Show Gist options
  • Save Paebbels/0a24ee8fbe2356f0562a6bdeb19b6c46 to your computer and use it in GitHub Desktop.
Save Paebbels/0a24ee8fbe2356f0562a6bdeb19b6c46 to your computer and use it in GitHub Desktop.
Read and validate a XML file with lxml in Python.
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