No spaces in xml string, means no attributes will appear in tags.
Line-breaker should appear once and only once before every '<' and after every '>'.
Tags change indents when they appear.
My Code
#!/usr/bin/python
import sys
import re
def format_one_line_xml(xml: str) -> str:
"""One line xml has no space or line break.
Return formatted xml with 4-space indents.
"""
lines = []
indent_count = 0
xml = re.sub(r'(<[^>]*>)', r'\n\1\n', xml)
for line in xml.split('\n'):
if line:
if line.startswith('</'):
indent_count -= 1
lines.append("{}{}".format(' ' * 4 * indent_count, line))
if line.startswith('<') and not line.endswith('/>') and not line.startswith('</') \
and not line.startswith('<!'):
indent_count += 1
return '\n'.join(lines)
def main():
"""Main function"""
xml = sys.argv[1]
print(format_one_line_xml(xml))
if __name__ == '__main__':
main()
Question_ID: Q001
Language: Python
Time Cost: 27-mins
Time Complexity: O(n)
Solution & Thoughts
My Code
Other
Comments are welcome.