XML 문서에 Processing Instruction 추가하기

Python3.6 · 2020. 1. 23. 12:10

Processing Instruction은 처리 명령으로 XML 문서에 대한 정보를 응용프로그램에 전달하는 역할을 한다.

XML 시작 부분에 등장하는 XML 선언이 처리 명령 중 하나인데

 

<? xml version = "1.0"?>

이렇게 생겼다.

 

그런데 나는 XML 선언 말고도 PI를 또 XML 내부에 추가해야됐다.

구글링으로도 자료가 많이 나오지 않아서 파이썬 라이브러리문서와 구글링으로 코드를 짰다.

코드가 돌아가고 XML 문서도 정상적으로 실행이 되어서 기록용으로 올려본다.

XML 문서 파싱 방법은 많이 나오는데.. 만드는 법은 찾기 어려웠다.

 

 

1
2
3
4
5
6
7
8
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)
 
pi = etree.ProcessingInstruction('PI''content')
article.insert(2, pi)
cs

 

ProcessingInstruction 메서드로 pi 객체를 만든 다음에 insert로 article 엘리먼트에 추가해줬다.

 

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">
  <?PI content?>
</article>
cs

 

이렇게 나온다.

 

 

 

참고자료

(1) http://www.hanbit.co.kr/channel/category/category_view.html?cms_code=CMS5868797159

(2) https://stackoverflow.com/questions/39115398/what-does-mean-in-xml

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

(4) https://www.programcreek.com/python/example/88299/xml.etree.ElementTree.ProcessingInstruction