본문 바로가기
파이썬

XML문서 파싱하고, 검색하는 방법에 대해 알아보자.

by 혜룐 2015. 11. 10.

ElementTree의 parse라는 함수를 이용해 xml을 파싱할수 있다.
어트리뷰트의 값 읽기
ParseXml이라는 클래스로 구현해보자. 생성자에 self.tree , self.note 변수를 만든다.
self.note.get("date") : date라는 attribute의 값을 읽는다.
태그 접근
def readTag(self):
[rootmaster python]# cat parseXml.py 
#coding=utf8
#from xml etree.ElementTree import parse
from xml.etree.ElementTree import *
class ParseXml():
def __init__(self, xmlFile):
self.xmlFile = xmlFile
tree = parse(self.xmlFile)
note = tree.getroot()
self.tree = tree
self.note = note
def readAttri(self):
## get메서드는 어트리뷰트의 값을 읽는다.
print self.note.get("date")
## get메서드 첫번째 인자에 해당되는 attribute값이 없을때 두번쨰인자를 리턴
print self.note.get("foo","default")
## keys는 모든 어트리뷰트의 키값을 리스트로 리턴
print self.note.keys()
## item은 key, value를 리턴
print self.note.items()
def readTag(self):
## note라는 태그 하위에 from과 일치 하는 첫번쨰 태그를 찾아서 리턴, 없으면 None
print self.note.find("from")
## note라는 태그 하위에 from과 일치하는 모든 태그를 리스트로 리턴
from_tags = self.note.findall("from")
for tag in from_tags:
print tag
## note라는 태그 하위에 from과 일치하는 첫번째 태그의 텍스트값을 리턴
print self.note.findtext("from")
## 특정 태그의 모든 하위 엘리먼트를 순차적으로 처리할때
print self.note.getiterator() 
print self.note.getiterator('from') 
print self.note.getchildren()
print ("=================================")
for parent in self.tree.getiterator():
for child in parent:
print child
def main():
x = ParseXml("note.xml");
x.readAttri()
x.readTag()
main()