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
'Python3.6' 카테고리의 다른 글
numpy.random.choice() 함수 사용하기 (0) | 2020.03.16 |
---|---|
XML 문서에 Processing Instruction 추가하기 (0) | 2020.01.23 |
알파벳에서 발음 구별 기호(Diacritic, Accent Mark) 분리하기 (0) | 2019.10.01 |
요소가 숫자로 구성된 리스트에 join 함수 사용하기 (0) | 2019.09.28 |
문자열에 리스트 요소 포함 여부 확인 (0) | 2019.09.20 |