Practical tutorial on combining python and XML
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 name="index" title="Home page"> <h1>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 href="interests/shouting.html" rel="external nofollow" >Shouting</a></li> <li><a href="interests/sleeping.html" rel="external nofollow" >Sleeping</a></li> <li><a href="interests/eating.html" rel="external nofollow" >Eating</a></li> </ul> </page> <directory name="interests"> <page name="shouting" title="Shouting"> <h1>shouting page</h1> <p>....</p> </page> <page name="sleeping" title="Sleeping"> <h1>sleeping page</h1> <p>...</p> </page> <page name="eating" title="Eating"> <h1>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('<' + name) for key, val in attrs.items(): self.out.write(' %s="%s"' %(key, val)) 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('<html>\n <head>\n <title>') self.out.write(title) self.out.write('</title>\n </head>\n <body>\n') def writeFooter(self): self.out.write('\n </body>\n</html>\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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.
