python XML parsing

Nov 23, 2016 pm 01:58 PM

What is XML?

XML refers to eXtensible Markup Language. You can learn XML tutorials through this site

XML is designed to transmit and store data.

XML is a set of rules that define semantic markup that divides a document into components and identifies those components.

It is also a meta-markup language, that is, it defines a syntactic language used to define other semantic and structured markup languages ​​related to specific fields.

Python’s parsing of XML

Common XML programming interfaces include DOM and SAX. These two interfaces process XML files in different ways, and of course the usage scenarios are also different.

Python has three methods to parse XML, SAX, DOM, and ElementTree:

1.SAX (simple API for XML)

pyhton The standard library contains a SAX parser. SAX uses an event-driven model, through the process of parsing XML Trigger events one by one and call user-defined callback functions to process XML files.

2.DOM (Document Object Model)

parses XML data into a tree in memory, and operates XML by operating on the tree.

3.ElementTree (Element Tree)

ElementTree is like a lightweight DOM with a convenient and friendly API. The code has good usability, is fast, and consumes less memory.

Note: Because DOM needs to map XML data to a tree in memory, it is relatively slow and consumes more memory. SAX streaming reading of XML files is faster and takes up less memory, but requires the user to implement a callback function. (handler).

The content of the XML example file movies.xml used in this chapter is as follows:

< type>War, Thriller

DVD

2003

PG

10< /stars>

Talk about a US-Japan war

Anime, Science Fiction< /type>

DVD

1989

R

8< /stars>

< ;description>A schientific fiction

Anime, Action

DVD< /format>

4

PG

10

V ash the Stampede!

Comedy

VHS

PG< /rating>

2

Viewable boredom

python use SAX parses xml

SAX is an event-driven API.

Using SAX to parse XML documents involves two parts: the parser and the event handler.

The parser is responsible for reading the XML document and sending events to the event processor, such as element start and element end events;

The event processor is responsible for responding to the event and processing the passed XML data.

1. Process large files;

2. Only need part of the file, or only need specific information from the file.

3. When you want to build your own object model.

To use sax to process xml in python, you must first introduce the parse function in xml.sax and the ContentHandler in xml.sax.handler.

ContentHandler class method introduction

characters(content) method

Calling timing:

Starting from the line, before encountering the label, there are characters, and the value of content is these strings.

From one label, there are characters before encountering the next label, and the value of content is these strings.

From a label, there are characters before encountering the line terminator, and the value of content is these strings. The

tag can be a start tag or an end tag.

startDocument() method

is called when the document is started.

endDocument() method

is called when the parser reaches the end of the document. The

startElement(name, attrs) method

is called when an XML start tag is encountered. name is the name of the tag, and attrs is the attribute value dictionary of the tag.

endElement(name) method

is called when an XML end tag is encountered.

make_parser method

The following method creates a new parser object and returns it.

xml.sax.make_parser([parser_list])

Parameter description:

parser_list - optional parameters, parser list

parser method

The following method creates a SAX parser device and Parse xml document:

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

Parameter description:

xmlfile - xml file name

contenthandler - must be a ContentHan dler object

errorhandler - If this parameter is specified, errorhandler must be a SAX ErrorHandler object

parseString method

parseString method creates an XML parser and parses an xml string:

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

Parameter description:

xmlstring - xml string

contenthandler - must be a ContentHandler object

errorhandler - if this parameter is specified, errorhandler must be a SAX ErrorHandler object

Python Parse XML instance

#!/usr/bin/python

import xml.sax

class MovieHandler( xml.sax.ContentHandler ):

def __init__(self):

self .CurrentData = ""

         self.type                                                                                                                                               . ""

 self.description = ""

# Element start event processing

def startElement(self, tag, attributes):

self.CurrentData = tag

if tag == "movie":

print "***** Movie*****"

                                                                                                                                           Movie**** if self. CurrentData == "type":

                                                                                                                                             CurrentData    == " year":

                                                                                                                                                                         .

T Print "start:", seld.stars

elif Self.currentData == "Description":

Print "Description:", Self.Descript

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 文档请查阅Python SAX APIs

使用xml.dom解析xml

文件对象模型(Document Object Model,简称DOM),是W3C组织推荐的处理可扩展置标语言的标准编程接口。

一个 DOM 的解析器在解析一个 XML 文档时,一次性读取整个文档,把文档中所有元素保存在内存中的一个树结构里,之后你可以利用DOM 提供的不同的函数来读取或修改文档的内容和结构,也可以把修改过的内容写入xml文件。

python中用xml.dom.minidom来解析xml文件,实例如下:

#!/usr/bin/python

 

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

   

The execution result of the above program is as follows:

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


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

See all articles