XML 문서에 주석 달기

Python3.6 · 2020. 1. 23. 11:56
1
2
3
4
5
6
7
from lxml import etree
 
NSMAP = {'mml''http://www.w3.org/1998/Math/MathML''xlink''http://www.w3.org/1999/xlink'}
article = etree.Element("article", {'article-type''research-article''dtd-version''1.1d3',
                                        '{http://www.w3.org/XML/1998/namespace}lang''en'}, nsmap=NSMAP)
comment = etree.Comment('xml annotation')
article.insert(2, comment)
cs

 

xml 문서를 만들다가 주석을 같이 달아줄 일이 생겼는데

수동으로 직접 다는 것 말고 자동으로 파일 생성하면서 만드는 방법이다.

insert 메서드에서 2는 코멘트 위치를 의미하고 마이너스가 붙으면 해당 엘리먼트의 앞에서부터 주석이 달린다.

insert는 메서드 하나씩 검색해보다가 발견한건데 검색해보니 append 메서드를 더 많이 쓰는 것 같다.

 

1
etree.tostring(article, pretty_print=True, encoding='UTF-8')
cs

 

tostring으로 프린트해보면

 

1
2
3
<article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" article-type="research-article" dtd-version="1.1d3" xml:lang="en">
  <!--xml annotation-->
</article>
cs

 

이렇게 결과가 나온다.

xml 문서에 주석을 다는 경우가 별로 없는지 생각보다 검색이 어려웠다.

 

 

참고자료

https://docs.python.org/2/library/xml.etree.elementtree.html