산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> python

Python XML Parser Tutorial:xml 파일 읽기 예제(Minidom, ElementTree)

XML이란 무엇입니까?

XML은 eXtensible Markup Language의 약자입니다. 중소량의 데이터를 저장 및 전송하도록 설계되었으며 구조화된 정보를 공유하는 데 널리 사용됩니다.

Python을 사용하면 XML 문서를 구문 분석하고 수정할 수 있습니다. XML 문서를 구문 분석하려면 전체 XML 문서가 메모리에 있어야 합니다. 이 튜토리얼에서는 Python에서 XML minidom 클래스를 사용하여 XML 파일을 로드하고 구문 분석하는 방법을 살펴봅니다.

이 튜토리얼에서 배울 것입니다-

minidom을 사용하여 XML을 구문 분석하는 방법

구문 분석할 샘플 XML 파일을 만들었습니다.

1단계) 파일 내부에서 이름, 성, 집 및 전문 분야(SQL, Python, 테스팅 및 비즈니스)를 볼 수 있습니다.


2단계) 문서를 구문 분석하면 "노드 이름"을 인쇄합니다. 문서 루트 및 "firstchild tagname" . 태그 이름과 노드 이름은 XML 파일의 표준 속성입니다.

참고 :

Nodename 및 자식 tagname은 XML dom의 표준 이름 또는 속성입니다. 이러한 유형의 명명 규칙에 익숙하지 않은 경우

3단계) XML 문서에서 XML 태그 목록을 호출하여 인쇄할 수도 있습니다. 여기에서 SQL, Python, 테스트 및 비즈니스와 같은 기술 세트를 인쇄했습니다.

XML 노드 생성 방법

"createElement" 함수를 사용하여 새 속성을 만든 다음 이 새 속성 또는 태그를 기존 XML 태그에 추가할 수 있습니다. XML 파일에 새 태그 "BigData"를 추가했습니다.

  1. 기존 XML 태그에 새 속성(BigData)을 추가하려면 코딩해야 합니다.
  2. 그런 다음 기존 XML 태그에 새 속성이 추가된 XML 태그를 인쇄해야 합니다.

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")
    
# create 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"))

    # create 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

요약:

Python을 사용하면 한 번에 한 줄만이 아니라 전체 XML 문서를 한 번에 구문 분석할 수 있습니다. XML 문서를 구문 분석하려면 전체 문서가 메모리에 있어야 합니다.


python

  1. 파이썬 파일 I/O
  2. Java BufferedReader:예제를 사용하여 Java에서 파일을 읽는 방법
  3. EXAMPLE이 있는 Python String strip() 함수
  4. 파이썬 문자열 길이 | len() 메서드 예제
  5. Python 튜토리얼의 Yield:Generator &Yield vs Return 예제
  6. 예제가 있는 컬렉션의 Python 카운터
  7. Python의 Enumerate() 함수:루프, 튜플, 문자열(예제)
  8. Python 파일 존재 여부 확인 | 파이썬에서 디렉토리가 존재하는지 확인하는 방법
  9. Python JSON:인코딩(덤프), 디코딩(로드) 및 JSON 파일 읽기
  10. 예제가 있는 Python 목록 index()