Home  >  Article  >  Backend Development  >  Practical tutorial on combining python and XML

Practical tutorial on combining python and XML

php中世界最好的语言
php中世界最好的语言Original
2018-04-09 14:34:541233browse

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('<&#39; + name)
            for key, val in attrs.items():
                self.out.write(&#39; %s="%s"&#39; %(key, val))
            self.out.write(&#39;>')
    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!

Statement:
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