XML 포매터
XML을 정형화·검증·최소화합니다.
들여쓰기:
자주 묻는 질문
코드 구현
import xml.etree.ElementTree as ET
import xml.dom.minidom
# Format (pretty-print) XML
raw_xml = '<root><person><name>Alice</name><age>30</age></person></root>'
# Method 1: minidom (adds XML declaration)
dom = xml.dom.minidom.parseString(raw_xml)
pretty = dom.toprettyxml(indent=' ')
# Remove the extra XML declaration line if needed
lines = pretty.split('\n')
if lines[0].startswith('<?xml'):
pretty = '\n'.join(lines[1:])
print(pretty)
# Method 2: ElementTree (parse and re-serialize)
ET.indent # Available in Python 3.9+
root = ET.fromstring(raw_xml)
ET.indent(root, space=' ')
formatted = ET.tostring(root, encoding='unicode')
print(formatted)
# Minify XML
minified = ''.join(line.strip() for line in raw_xml.splitlines())
print(minified)Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.