Refactored formatter
This commit is contained in:
@@ -1,31 +1,18 @@
|
||||
from lxml import etree
|
||||
from io import BytesIO
|
||||
|
||||
def prettify(source: str) -> str:
|
||||
"""Method used to pretty format given XML
|
||||
|
||||
:param source: XML
|
||||
:return: prettified XML
|
||||
def format(source: str, prettify: bool) -> str:
|
||||
"""Method used to format XML
|
||||
|
||||
:param source: XML to format
|
||||
:param prettify: sets if XML must be prettified
|
||||
(have added intendations etc.) or not
|
||||
:return: formatted XML
|
||||
"""
|
||||
prolog = ""
|
||||
prolog_start = source.find("<?")
|
||||
|
||||
if prolog_start != -1:
|
||||
prolog_end = source.find("?>") + 2
|
||||
prolog = source[prolog_start:prolog_end] + "\n"
|
||||
source = source[prolog_end: ]
|
||||
|
||||
parser = etree.XMLParser(remove_blank_text=True)
|
||||
xml = etree.fromstring(source, parser=parser)
|
||||
return prolog + etree.tostring(xml, pretty_print=True).decode()
|
||||
|
||||
def minimize(source: str) -> str:
|
||||
"""Method used to minimize XML by deleting not needed whitespaces.
|
||||
|
||||
:param source: XML
|
||||
:return: minimized XML
|
||||
"""
|
||||
|
||||
# Prolog is removed when XML is parsed
|
||||
# so program has to copy it
|
||||
prolog = ""
|
||||
prolog_start = source.find("<?")
|
||||
|
||||
@@ -34,9 +21,14 @@ def minimize(source: str) -> str:
|
||||
prolog = source[prolog_start:prolog_end]
|
||||
source = source[prolog_end: ]
|
||||
|
||||
byte_input = BytesIO(source.encode("utf-8"))
|
||||
parser = etree.XMLParser(remove_blank_text=True)
|
||||
xml = etree.fromstring(source, parser=parser)
|
||||
return prolog + etree.tostring(xml, pretty_print=False).decode()
|
||||
xml = etree.parse(byte_input, parser=parser)
|
||||
|
||||
if prettify:
|
||||
prolog += "\n"
|
||||
|
||||
return prolog + etree.tostring(xml, pretty_print=prettify).decode()
|
||||
|
||||
|
||||
def xpath(source: str, xpath: str) -> str:
|
||||
|
||||
@@ -74,9 +74,9 @@ def process_xml(request: request, type: str) -> str:
|
||||
elif (type == "xpath"):
|
||||
response_json['result'] = Parser.xpath(data, process)
|
||||
elif (type == "prettify"):
|
||||
response_json['result'] = Parser.prettify(data)
|
||||
response_json['result'] = Parser.format(data, True)
|
||||
elif (type == "minimize"):
|
||||
response_json['result'] = Parser.minimize(data)
|
||||
response_json['result'] = Parser.format(data, False)
|
||||
else:
|
||||
raise ValueError("Valid operation types are: xsd, xslt, xpath")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user