Files
release11-tools/Backend-libXML/Parser.py
2023-01-26 13:41:19 +01:00

67 lines
1.6 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: If the validation was successful or not
:rtype: bool
"""
xml_schema = etree.XMLSchema(etree.XML(xsd))
xml = etree.XML(source)
return xml_schema.validate(xml)
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)