Python XML 파일 – 읽고, 쓰고, 구문 분석하는 방법
⚡ 스마트 요약
Python XML 처리를 통해 내장된 minidom 및 ElementTree 모듈을 사용하여 XML 문서를 읽고 쓰고 구문 분석할 수 있습니다. minidom 클래스는 파일을 DOM으로 메모리에 로드하는 반면, ElementTree는 더 빠르고 효율적인 방식을 제공합니다. Pythonic 트리 API.

아래 섹션에서는 XML 파일의 구문 분석, 쓰기 및 읽기에 대해 설명합니다. Python.
XML이란 무엇입니까?
XML은 eXtensible Markup Language를 의미합니다. 중소 규모의 데이터를 저장하고 전송하도록 설계되었으며 구조화된 정보를 공유하는 데 널리 사용됩니다.
Python XML 문서를 구문 분석하고 수정할 수 있습니다. XML 문서를 구문 분석하려면 전체 XML 문서가 메모리에 있어야 합니다. 이 튜토리얼에서는 XML minidom 클래스를 사용하는 방법을 살펴보겠습니다. Python XML 파일을 로드하고 구문 분석합니다.
minidom을 사용하여 XML을 구문 분석하는 방법
구문 분석할 샘플 XML 파일을 만들었습니다.
1단계) 샘플 XML 파일 생성
파일 내부에는 이름, 성, 집, 전문분야(SQL, Python(테스팅 및 비즈니스).
2단계) 구문 분석 기능을 사용하여 XML 파일을 로드하고 구문 분석합니다.
문서를 분석한 후에는 문서의 루트 노드 이름과 첫 번째 자식 태그 이름을 출력합니다. 태그 이름과 노드 이름은 XML 파일의 표준 속성입니다.
- xml.dom.minidom 모듈을 임포트하고 파싱해야 할 파일(myxml.xml)을 선언합니다.
- 이 파일에는 이름, 성, 집, 전문 지식 등과 같은 직원에 대한 몇 가지 기본 정보가 포함되어 있습니다.
- XML 파일을 로드하고 구문 분석하기 위해 XML minidom의 구문 분석 기능을 사용합니다.
- 우리는 doc이라는 변수를 가지고 있으며, doc은 parse 함수의 결과를 받습니다.
- 파일에서 노드 이름과 자식 태그 이름을 출력하고 싶으므로, 출력 함수 내에 이를 선언합니다.
- 코드 실행 - XML 파일의 노드 이름(#document)과 XML 파일의 첫 번째 하위 태그 이름(직원)을 인쇄합니다.
주의 사항노드 이름과 자식 태그 이름은 XML DOM의 표준 이름 또는 속성입니다.
3단계) XML 문서에서 XML 태그 목록을 불러와 출력합니다.
다음으로, XML 문서에서 XML 태그 목록을 불러와 출력할 수도 있습니다. 여기서는 SQL과 같은 스킬 목록을 출력했습니다. Python, 지원 그리고 사업.
- 우리가 살펴볼 변수인 전문성을 선언합니다.trac직원이 가진 모든 전문 분야 이름
- "getElementsByTagName"이라는 dom 표준 함수를 사용하세요.
- 이것은 Skill이라는 모든 요소를 가져옵니다.
- 각 스킬 태그에 대해 반복문을 선언하세요.
- 코드를 실행하면 네 가지 기술 목록이 표시됩니다.
XML 노드를 작성하는 방법
"createElement" 함수를 사용하여 새 속성을 생성한 다음 이 새 속성이나 태그를 기존 XML 태그에 추가할 수 있습니다. XML 파일에 새 태그 "BigData"를 추가했습니다.
- 기존 XML 태그에 새 속성(BigData)을 추가하는 코드를 작성해야 합니다.
- 그다음에는 기존 XML 태그에 새 속성이 추가된 XML 태그를 출력해야 합니다.
- 새로운 XML 태그를 추가하고 문서에 삽입하려면 "doc.createElement" 코드를 사용합니다.
- 이 코드는 새로운 속성인 "빅데이터"에 대한 새로운 스킬 태그를 생성합니다.
- 이 스킬 태그를 문서의 첫 번째 하위 요소(직원)에 추가하세요.
- 코드를 실행하면 "빅데이터"라는 새로운 태그가 다른 전문 분야 목록과 함께 나타납니다.
XML 파서 예
Python 2 예
import xml.dom.minidom def main(): # use the parse() function to load and parse an XML file doc = xml.dom.minidom.parse("Myxml.xml"); # print out the document node and the name of the first child tag print doc.nodeName print doc.firstChild.tagName # get a list of XML tags from the document and print each one expertise = doc.getElementsByTagName("expertise") print "%d expertise:" % expertise.length for skill in expertise: print skill.getAttribute("name") #Write a new XML tag and add it into the document newexpertise = doc.createElement("expertise") newexpertise.setAttribute("name", "BigData") doc.firstChild.appendChild(newexpertise) print " " expertise = doc.getElementsByTagName("expertise") print "%d expertise:" % expertise.length for skill in expertise: print skill.getAttribute("name") if name == "__main__": main();
Python 3 예
import xml.dom.minidom def main(): # use the parse() function to load and parse an XML file doc = xml.dom.minidom.parse("Myxml.xml"); # print out the document node and the name of the first child tag print (doc.nodeName) print (doc.firstChild.tagName) # get a list of XML tags from the document and print each one expertise = doc.getElementsByTagName("expertise") print ("%d expertise:" % expertise.length) for skill in expertise: print (skill.getAttribute("name")) # Write a new XML tag and add it into the document newexpertise = doc.createElement("expertise") newexpertise.setAttribute("name", "BigData") doc.firstChild.appendChild(newexpertise) print (" ") expertise = doc.getElementsByTagName("expertise") print ("%d expertise:" % expertise.length) for skill in expertise: print (skill.getAttribute("name")) if __name__ == "__main__": main();
ElementTree를 사용하여 XML을 구문 분석하는 방법
ElementTree는 XML을 조작하기 위한 API입니다. ElementTree를 사용하면 XML 파일을 쉽게 처리할 수 있습니다.
다음 XML 문서를 샘플 데이터로 사용하고 있습니다.
<data> <items> <item name="expertise1">SQL</item> <item name="expertise2">Python</item> </items> </data>
ElementTree를 사용하여 XML 읽기:
먼저 xml.etree.ElementTree 모듈을 가져와야 합니다.
import xml.etree.ElementTree as ET
이제 루트 요소를 가져오겠습니다.
root = tree.getroot()
다음은 위 XML 데이터를 읽는 전체 코드입니다.
import xml.etree.ElementTree as ET tree = ET.parse('items.xml') root = tree.getroot() # all items data print('Expertise Data:') for elem in root: for subelem in elem: print(subelem.text)
출력:
Expertise Data: SQL Python




