Latest web development tutorials

파이썬 XML 파싱

XML은 무엇입니까?

XML은 확장 마크 업 언어(전자 X tensible M의 arkup의 L의 anguage을 의미한다). 이 사이트를 통해 배울 수있는 XML 자습서

XML을 전송하고 데이터를 저장하도록 설계되었습니다.

XML 태그의 의미를 정의하는 규칙의 집합입니다,이 태그는 많은 부품 식별 할 수있는 이러한 부분으로 나누어 문서화합니다.

또한 다른 도메인 - 특정 의미, 구조화 된 마크 업 언어를 정의하는 데 사용되는 언어의 구문을 정의하는 메타 마크 업 언어이다.


XML 구문 분석을위한 파이썬

공통 DOM과 XML 프로그래밍 인터페이스 SAX, XML과 두 개의 서로 다른 인터페이스는 물론 방법, 다른 경우의 사용을 파일.

세 가지 방법이 있습니다 파이썬 구문 분석 XML, SAX, DOM, 및 ElementTree :

1.SAX (XML에 대한 간단한 API)

파이썬 표준 라이브러리는 XML을 구문 분석 및 XML 파일을 처리하기 위해 사용자 정의 콜백 함수를 호출하는 과정에서 하나의 이벤트에 의해 트리거 SAX 파서는 이벤트 구동 모델과 SAX를 포함합니다.

2.DOM (문서 객체 모델)

XML 데이터는 XML을 조작 트리를 통해 동작하는 메모리의 트리로 파싱된다.

3.ElementTree (요소 트리)

편리하고 쉬운 API와 경량 DOM 등 ElementTree. 코드 빠른 가용성, 적은 메모리를 소비합니다.

주 : 메모리 트리에 XML 데이터를 매핑해야 DOM으로 인해 하나의 느린 번째 메모리가 더 소비하고, SAX 스트리밍은 XML 파일을 빠르게 판독 (처리기 적은 메모리를 차지하지만 콜백을 구현하도록 사용자를 필요 ).

다음과 같이 XML 인스턴스 문서 movies.xml이 섹션을 사용하여 읽

<collection shelf="New Arrivals">
<movie title="Enemy Behind">
   <type>War, Thriller</type>
   <format>DVD</format>
   <year>2003</year>
   <rating>PG</rating>
   <stars>10</stars>
   <description>Talk about a US-Japan war</description>
</movie>
<movie title="Transformers">
   <type>Anime, Science Fiction</type>
   <format>DVD</format>
   <year>1989</year>
   <rating>R</rating>
   <stars>8</stars>
   <description>A schientific fiction</description>
</movie>
   <movie title="Trigun">
   <type>Anime, Action</type>
   <format>DVD</format>
   <episodes>4</episodes>
   <rating>PG</rating>
   <stars>10</stars>
   <description>Vash the Stampede!</description>
</movie>
<movie title="Ishtar">
   <type>Comedy</type>
   <format>VHS</format>
   <rating>PG</rating>
   <stars>2</stars>
   <description>Viewable boredom</description>
</movie>
</collection>

SAX를 사용하여 파이썬 XML 파싱

SAX는 이벤트 중심의 API이다.

파서 이벤트 핸들러 : XML 문서를 파싱 사용 SAX는 두 부분을 포함한다.

파서는 XML 문서를 판독 할 책임이 있으며, 소자는 소자 종료 이벤트와 같은 시작 이벤트의 이벤트 핸들러를 보낸다;

이벤트 핸들러는 이벤트에 따라, 처리를위한 XML 데이터 전송을 담당한다.

  • 1, 대용량 파일의 처리;
  • 이 파일의 내용의 일부 또는 단순히 파일로부터 특정 정보를 획득한다.
  • 3 시간 자신의 객체 모델을 구축 할 수 있습니다.

색소폰 먼저 구문 분석 함수에 도입 된 방식으로 XML의 xml.sax뿐만 아니라, 파이썬에서의 ContentHandler xml.sax.handler를 사용합니다.

의 ContentHandler 클래스 메서드 소개

문자 (콘텐츠) 방법

호출 시점 :

줄의 시작 부분에서 레이블을 경험하기 전에 이러한 문자열의 문자, 콘텐츠 가치가있다.

레이블에서, 다음 만남 전에 레이블, 문자의 존재, 이러한 문자열의 내용 값입니다.

레이블에서, 줄 끝 문자의 존재, 이러한 문자열의 내용 값을 발생하기 전에.

태그는 태그의 시작 부분이 될 수 있고, 그것은 라벨의 단부 일 수있다.

있으며, StartDocument () 메소드

문서의 시작은했다.

로부터 endDocument () 메소드

호출은 문서 파서 다하면.

의 startElement (이름, attrs에) 방법

발생 XML 시작 태그를 호출, 이름이 태그의 이름 attrs에는 사전 속성 값 태그입니다.

하는 endElement (이름) 방법

전화는 XML 끝 태그가 발생했습니다.


make_parser 방법

다음 방법은 새로운 파서 객체 반환을 만듭니다.

xml.sax.make_parser( [parser_list] )

매개 변수 설명 :

  • parser_list - 선택적 매개 변수, 파서 목록

파서 방법

다음 방법은 SAX 파서를 생성하고 XML 문서를 구문 분석 :

xml.sax.parse( xmlfile, contenthandler[, errorhandler])

매개 변수 설명 :

  • XMLFILE - xml 파일 이름
  • ContentHandler의 - 한의 ContentHandler의 대상이어야합니다
  • ErrorHandler를 -이 매개 변수를 지정하는 경우, ErrorHandler를은 SAX ErrorHandler를 개체 수 있어야합니다

parseString을 방법

방법을 parseString을하는 것은 XML 파서를 만들고 XML 문자열을 구문 분석 :

xml.sax.parseString(xmlstring, contenthandler[, errorhandler])

매개 변수 설명 :

  • xmlString을 - XML 문자열
  • ContentHandler의 - 한의 ContentHandler의 대상이어야합니다
  • ErrorHandler를 -이 매개 변수를 지정하는 경우, ErrorHandler를은 SAX ErrorHandler를 개체 수 있어야합니다

파이썬 구문 분석 XML 인스턴스

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import xml.sax

class MovieHandler( xml.sax.ContentHandler ):
   def __init__(self):
      self.CurrentData = ""
      self.type = ""
      self.format = ""
      self.year = ""
      self.rating = ""
      self.stars = ""
      self.description = ""

   # 元素开始事件处理
   def startElement(self, tag, attributes):
      self.CurrentData = tag
      if tag == "movie":
         print "*****Movie*****"
         title = attributes["title"]
         print "Title:", title

   # 元素结束事件处理
   def endElement(self, tag):
      if self.CurrentData == "type":
         print "Type:", self.type
      elif self.CurrentData == "format":
         print "Format:", self.format
      elif self.CurrentData == "year":
         print "Year:", self.year
      elif self.CurrentData == "rating":
         print "Rating:", self.rating
      elif self.CurrentData == "stars":
         print "Stars:", self.stars
      elif self.CurrentData == "description":
         print "Description:", self.description
      self.CurrentData = ""

   # 内容事件处理
   def characters(self, content):
      if self.CurrentData == "type":
         self.type = content
      elif self.CurrentData == "format":
         self.format = content
      elif self.CurrentData == "year":
         self.year = content
      elif self.CurrentData == "rating":
         self.rating = content
      elif self.CurrentData == "stars":
         self.stars = content
      elif self.CurrentData == "description":
         self.description = content
  
if ( __name__ == "__main__"):
   
   # 创建一个 XMLReader
   parser = xml.sax.make_parser()
   # turn off namepsaces
   parser.setFeature(xml.sax.handler.feature_namespaces, 0)

   # 重写 ContextHandler
   Handler = MovieHandler()
   parser.setContentHandler( Handler )
   
   parser.parse("movies.xml")

다음과 같이 위의 코드가 실행된다 :

*****Movie*****
Title: Enemy Behind
Type: War, Thriller
Format: DVD
Year: 2003
Rating: PG
Stars: 10
Description: Talk about a US-Japan war
*****Movie*****
Title: Transformers
Type: Anime, Science Fiction
Format: DVD
Year: 1989
Rating: R
Stars: 8
Description: A schientific fiction
*****Movie*****
Title: Trigun
Type: Anime, Action
Format: DVD
Rating: PG
Stars: 10
Description: Vash the Stampede!
*****Movie*****
Title: Ishtar
Type: Comedy
Format: VHS
Rating: PG
Stars: 2
Description: Viewable boredom

전체 SAX API 문서는 참조하십시오 파이썬 SAX API를


xml.dom 구문 분석 XML을 사용

(DOM이라 문서 객체 모델) 문서 객체 모델, 그것은 W3C 권장 치료 확장 마크 업 언어 표준 프로그래밍 인터페이스입니다.

XML 문서를 구문 분석하는 DOM 파서에서, 한 번에 메모리에 트리 구조에 저장된 문서의 모든 요소를 ​​전체 문서를 읽고, 당신은 읽거나 문서를 수정할 수있는 다양한 기능을 제공하기 위해 DOM을 사용할 수 있습니다 콘텐츠 및 구조는 XML 파일의 내용을 기록하도록 수정된다.

다음과 같이 XML 문서를 구문 분석하는 xml.dom.minidom와 파이썬, 예는 다음과 같습니다

#!/usr/bin/python
# -*- coding: UTF-8 -*-

from xml.dom.minidom import parse
import xml.dom.minidom

# 使用minidom解析器打开 XML 文档
DOMTree = xml.dom.minidom.parse("movies.xml")
collection = DOMTree.documentElement
if collection.hasAttribute("shelf"):
   print "Root element : %s" % collection.getAttribute("shelf")

# 在集合中获取所有电影
movies = collection.getElementsByTagName("movie")

# 打印每部电影的详细信息
for movie in movies:
   print "*****Movie*****"
   if movie.hasAttribute("title"):
      print "Title: %s" % movie.getAttribute("title")

   type = movie.getElementsByTagName('type')[0]
   print "Type: %s" % type.childNodes[0].data
   format = movie.getElementsByTagName('format')[0]
   print "Format: %s" % format.childNodes[0].data
   rating = movie.getElementsByTagName('rating')[0]
   print "Rating: %s" % rating.childNodes[0].data
   description = movie.getElementsByTagName('description')[0]
   print "Description: %s" % description.childNodes[0].data

다음과 같이, 상기 절차의 결과이다 :

Root element : New Arrivals
*****Movie*****
Title: Enemy Behind
Type: War, Thriller
Format: DVD
Rating: PG
Description: Talk about a US-Japan war
*****Movie*****
Title: Transformers
Type: Anime, Science Fiction
Format: DVD
Rating: R
Description: A schientific fiction
*****Movie*****
Title: Trigun
Type: Anime, Action
Format: DVD
Rating: PG
Description: Vash the Stampede!
*****Movie*****
Title: Ishtar
Type: Comedy
Format: VHS
Rating: PG
Description: Viewable boredom

전체 DOM의 API 설명서를 참조하시기 바랍니다 파이썬은 DOM API를 .