56 lines
1.5 KiB
Python
56 lines
1.5 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
|
|
:param xpath: XPath query used for selection
|
|
:return: Nodes selected using XPath
|
|
"""
|
|
root = etree.XML(source)
|
|
nsmap = root.nsmap
|
|
|
|
# LXML doesn't accept namespace with None key,
|
|
# so it need to be deleted if exists
|
|
try:
|
|
nsmap.pop(None)
|
|
except KeyError:
|
|
print(end="")
|
|
|
|
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: If the validation was successful or not
|
|
"""
|
|
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: Transformed XML string
|
|
: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) |