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()
'파이썬' 카테고리의 다른 글
rss , Atom 그리고 RDF를 포함해, 피드를 구문 분석하는 파이썬 라이브러리 모듈인 feedparser (0) | 2015.11.10 |
---|---|
multiprocessing : Process-based "threading" inteface (0) | 2015.11.10 |
XML을 처리 하는 파이썬 라이브러리중 ElementTree에 대해 알아보자.( xml 생성) (0) | 2015.11.10 |
시스템 명령행 인자와 파일다루기 예제(간단한 메모장 만들기) (0) | 2015.11.10 |
파이썬 Queue - a aynchronized queue class (0) | 2015.11.10 |