Skip to content

Instantly share code, notes, and snippets.

@Ch3shireDev
Created June 28, 2021 06:23
Show Gist options
  • Save Ch3shireDev/0b07ee166dfa0f2223ef950fdc14e663 to your computer and use it in GitHub Desktop.
Save Ch3shireDev/0b07ee166dfa0f2223ef950fdc14e663 to your computer and use it in GitHub Desktop.
xsd
import xmlschema
import json
import yaml
import glob
ns = '{http://www.w3.org/XML/1998/namespace}'
xs = '{http://www.w3.org/2001/XMLSchema}'
def get_docs(element, lang):
if hasattr(element.annotation, 'documentation'):
for doc in element.annotation.documentation:
if f'{ns}lang' in doc.attrib and lang in doc.attrib[f'{ns}lang'] and doc.text:
return doc.text.strip()
if hasattr(element.type.annotation, 'documentation'):
for doc in element.type.annotation.documentation:
if f'{ns}lang' in doc.attrib and lang in doc.attrib[f'{ns}lang'] and doc.text:
return doc.text.strip()
if element.type.base_type and hasattr(element.type.base_type.annotation, 'documentation'):
for doc in element.type.base_type.annotation.documentation:
if f'{ns}lang' in doc.attrib and lang in doc.attrib[f'{ns}lang'] and doc.text:
return doc.text.strip()
return ''
def get_dictionary(element, path=[]):
element_doc_pl = get_docs(element, 'pl')
element_doc_en = get_docs(element, 'en')
elements = []
attributes = []
element_path = '/'.join(['']+path)
for attr in element.attributes:
attr = element.attributes[attr]
doc_pl = get_docs(attr, 'pl')
doc_en = get_docs(attr, 'en')
attr_path = '/'.join(['']+path+[f'@{attr}'])
attributes.append({'name': attr, 'path': attr_path,
'doc_pl': doc_pl, 'doc_en': doc_en})
for child in element:
if child.local_name is None:
continue
if child.local_name == 'Signature':
continue
child_dict = get_dictionary(child, path+[child.local_name])
elements.append(child_dict)
return {'name': element.local_name,
'path': element_path,
'doc_pl': element_doc_pl,
'doc_en': element_doc_en,
'attributes': attributes,
'elements': elements}
def get_document(fname):
my_schema = xmlschema.XMLSchema(fname)
for key in my_schema.elements:
document = my_schema.elements[key]
document_tree = get_dictionary(document, [document.local_name])
doc_pl = None
doc_en = None
for element in document.source.parent_map:
if element.tag == f'{xs}documentation':
if f'{ns}lang' in element.attrib and element.attrib[f'{ns}lang'] == 'pl' and element.text:
doc_pl = element.text.strip()
if f'{ns}lang' in element.attrib and element.attrib[f'{ns}lang'] == 'en' and element.text:
doc_en = element.text.strip()
return {'name': document.name, 'document': document_tree, 'doc_pl': doc_pl, 'doc_en': doc_en}
documents = []
for fname in glob.glob('./xsd/full/AIS_Import_publiczna/*.xsd'):
document = get_document(fname)
if document:
documents.append(document)
with open('ais.yml', 'w+', encoding='utf-8') as f:
yaml.dump(documents, f, allow_unicode=True, Dumper=yaml.BaseDumper)
f.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment