from lxml import etree def prettify(source: str) -> str: xml = etree.XML(source) return etree.tostring(xml, pretty_print=True).decode() def minimize(source: str) -> str: xml = etree.XML(source) return etree.tostring(xml, pretty_print=False).decode() def xpath(source: str, xpath: str) -> str: """ Method used to get nodes from XML string using XPath :param source: XML string used for selection :param xpath: XPath query used for selection :return: Nodes selected using XPath """ root = etree.XML(source) nsmap = root.nsmap # LXML doesn't accept empty (None) namespace prefix, # so it need to be deleted if exists if None in nsmap: nsmap.pop(None) result = root.xpath(xpath, namespaces=nsmap) result_string = "" for e in result: result_string += etree.tostring(e, pretty_print=True).decode() + "\n" return result_string def xsd(source: str, xsd: str) -> bool: """ Method used to validate XML string against XSD schema :param source: XML string used for validation :param xsd: XSD schema to validate XML against :return: Message saying, if the validation was successful or not """ xml_schema = etree.XMLSchema(etree.XML(xsd)) xml = etree.XML(source) if xml_schema.validate(xml): return "XML is valid." else: return "XML is NOT valid." def xslt(source: str, xslt: str) -> str: """ Method used to transformate XML string using XSLT :param source: XML string to transform :param xslt: XSLT string used to transformate XML :return: Result of transformation """ xslt_transform = etree.XSLT(etree.XML(xslt)) xml = etree.XML(source) transformated = xslt_transform(xml) print(transformated) return str(transformated)