본문으로 바로가기

파이썬 XML Pretty 출력하기

category Language/Python 2020. 7. 15. 14:52
728x90

예제

xml.dom.minidom 은 xml 객체, xml 파일에서 dom 객체를 변환하기 위해 사용되는 모듈입니다.

import xml.dom.minidom

src_xml = '<?xml version="1.0" encoding="UTF-8" ?><employees><employee><Name>jvvp.tistory.com</Name></employee></employees>'
xml = xml.dom.minidom.parseString(src_xml)
pretty_xml = xml.toprettyxml()

print(src_xml)
print(pretty_xml)
더보기
<?xml version="1.0" encoding="UTF-8" ?><employees><employee><Name>jvvp.tistory.com</Name></employee></employees>
<?xml version="1.0" ?>
<employees>
        <employee>
                <Name>jvvp.tistory.com</Name>
        </employee>
</employees>

 

파일에도 쓰고 읽어 봅니다.

import xml.dom.minidom

src_xml = '<?xml version="1.0" encoding="UTF-8" ?><employees><employee><Name>jvvp.tistory.com</Name></employee></employees>'
xml = xml.dom.minidom.parseString(src_xml)
pretty_xml = xml.toprettyxml()

with open('src.xml', 'w', encoding='utf-8') as f:
    f.write(src_xml)
with open('pretty.xml', 'w', encoding='utf-8') as f:
    f.write(pretty_xml)

with open('src.xml', 'r', encoding='utf-8') as f:
    src_xml = f.read()
with open('pretty.xml', 'r', encoding='utf-8') as f:
    pretty_xml = f.read()

print(src_xml)
print(pretty_xml)
더보기
<?xml version="1.0" encoding="UTF-8" ?><employees><employee><Name>jvvp.tistory.com</Name></employee></employees>
<?xml version="1.0" ?>
<employees>
        <employee>
                <Name>jvvp.tistory.com</Name>
        </employee>
</employees>