69 lines
		
	
	
		
			1.7 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
			
		
		
	
	
			69 lines
		
	
	
		
			1.7 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
| from lxml import etree
 | |
| 
 | |
| 
 | |
| def xpath(source: str, xpath: str) -> str:
 | |
|     """
 | |
|     Method used to get nodes from XML string using XPath
 | |
| 
 | |
|     :param source: XML string used for selection
 | |
|     :type source: str
 | |
|     :param xpath: XPath query used for selection
 | |
|     :type xpath: str
 | |
|     :return: Nodes selected using XPath
 | |
|     :rtype: str
 | |
|     """
 | |
| 
 | |
|     
 | |
|     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
 | |
|     :type source: str
 | |
|     :param xsd: XSD schema to validate XML against
 | |
|     :type xsd: str
 | |
|     :return: Message saying, if the validation was successful or not
 | |
|     :rtype: str
 | |
|     """
 | |
|     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
 | |
|     :type source: str
 | |
|     :param xslt: XSLT string used to transformate XML
 | |
|     :type xslt: str
 | |
|     :return: Result of transformation
 | |
|     :rtype: str
 | |
|     """
 | |
|     xslt_transform = etree.XSLT(etree.XML(xslt))
 | |
| 
 | |
|     xml = etree.XML(source)
 | |
| 
 | |
|     transformated = xslt_transform(xml)
 | |
|     print(transformated)
 | |
|     return str(transformated) |