This time I will bring you a practical tutorial on combining python and XML. What are the precautions for combining python and XML? Here are practical cases, let’s take a look.
The name of this project is not called universal XML, it is better to call it automatic website construction. Based on an XML file, a website corresponding to the directory structure is generated, but only html is still too simple. If It would be more powerful if it could generate css together. This needs to be developed in the future. Let’s first study how to structure the HTML website. Since the website is generated through XML structure, everything should come from this XML file. Let’s first look at this XML file, website.xml:
<website> <page> <h1 id="Welcome-to-my-Home-page">Welcome to my Home page</h1> <p>Hi, there. My name is Mr.gumby,and this is my home page,here are some of my int:</p> <ul> <li><a>Shouting</a></li> <li><a>Sleeping</a></li> <li><a>Eating</a></li> </ul> </page> <directory> <page> <h1 id="shouting-page">shouting page</h1> <p>....</p> </page> <page> <h1 id="sleeping-page">sleeping page</h1> <p>...</p> </page> <page> <h1 id="Eating-page">Eating page</h1> <p>....</p> </page> </directory> </website>
With this file, let’s look at how to generate a website through this file.
First we have to parse this xml file. python parses xml the same as in java. There are two ways, SAX and DOM. The difference between the two processing methods is speed and scope. The former focuses on efficiency. Only a small part of the document is processed at a time, which can quickly and effectively utilize the memory. The latter is the opposite processing method. First, load all the documents into the memory and then process them. This is slower and consumes more memory. The only The advantage is that you can manipulate the entire document.
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. The latter class must be used in conjunction with the parse function. The usage is as follows: parse('xxx.xml',xxxHandler), the xxxHandler here needs to inherit the ContentHandler above, but just inherit it, no need to do anything. Then when the parse function processes the xml file, it will call the startElement function and endElement function in xxxHandler to start and end the tag in xml. The middle process uses a function named characters to process all the strings inside the tag. .
With the above understanding, we already know how to process xml files, and then look at the website.xml file, the source of evil, and analyze its structure. There are only two nodes: page and directory. It is obvious that page Represents a page, directory represents a directory.
So the idea of processing this xml file becomes clear. Read each node of the xml file, then determine whether it is a page or a directory. If it is a page, create an html page, and then write the contents of the node to the file. If directory is encountered, create a folder and then process the page node inside it (if it exists).
Let’s look at this part of the code. The implementation in the book is more complex and flexible. Let’s look at it first, and then analyze it.
from xml.sax.handler import ContentHandler from xml.sax import parse import os class Dispatcher: def dispatch(self, prefix, name, attrs=None): mname = prefix + name.capitalize() dname = 'default' + prefix.capitalize() method = getattr(self, mname, None) if callable(method): args = () else: method = getattr(self, dname, None) args = name, if prefix == 'start': args += attrs, if callable(method): method(*args) def startElement(self, name, attrs): self.dispatch('start', name, attrs) def endElement(self, name): self.dispatch('end', name) class WebsiteConstructor(Dispatcher, ContentHandler): passthrough = False def init(self, directory): self.directory = [directory] self.ensureDirectory() def ensureDirectory(self): path = os.path.join(*self.directory) print path print '----' if not os.path.isdir(path): os.makedirs(path) def characters(self, chars): if self.passthrough: self.out.write(chars) def defaultStart(self, name, attrs): if self.passthrough: self.out.write('') def defaultEnd(self, name): if self.passthrough: self.out.write('%s>' % name) def startDirectory(self, attrs): self.directory.append(attrs['name']) self.ensureDirectory() def endDirectory(self): print 'endDirectory' self.directory.pop() def startPage(self, attrs): print 'startPage' filename = os.path.join(*self.directory + [attrs['name']+'.html']) self.out = open(filename, 'w') self.writeHeader(attrs['title']) self.passthrough = True def endPage(self): print 'endPage' self.passthrough = False self.writeFooter() self.out.close() def writeHeader(self, title): self.out.write('\n \n <title>') self.out.write(title) self.out.write('</title>\n \n \n') def writeFooter(self): self.out.write('\n \n\n') parse('website.xml',WebsiteConstructor('public_html'))
It seems that the above analysis of this program is a bit more complicated, but the great man Maomao said that any complex program is a paper tiger. Then let's analyze this program again.
First of all, we see that this program has two classes. In fact, it can be regarded as one class because of inheritance.
Then let’s look at what else it has. In addition to the startElement, endElement and characters we analyzed, there are also startPage, endPage; startDirectory, endDirectory; defaultStart, defaultEnd; ensureDirectory; writeHeader, writeFooter; and dispatch. these functions. Except for dispatch, the previous functions are easy to understand. Each pair of functions simply processes the corresponding html tag and xml node. Dispatch is more complicated. The complexity is that it is used to dynamically combine functions and execute them.
The processing idea of dispatch is to first determine whether there is a corresponding function such as startPage based on the passed parameters (that is, the operation name and node name). If it does not exist, the default operation name: such as defaultStart will be executed.
After you understand each function one by one, you will know what the entire processing flow is like. First create a public_html file to store the entire website, then read the xml nodes, and call dispatch through startElement and endElement for processing. Then there is how dispatch calls the specific processing function. At this point, the analysis of this project has been completed.
The main content to master is the use of SAX to process XML in python, and the other is the use of functions in python, such as getattr, the asterisk when passing parameters...
I believe I have read this article You have mastered the case method. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
How does Python write data in a data frame to the database
Object life cycle in Python replication how to use
The above is the detailed content of Practical tutorial on combining python and XML. For more information, please follow other related articles on the PHP Chinese website!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software